虚拟公共基类方法在祖先中不可见

时间:2015-09-13 12:11:49

标签: c++ polymorphism

编译以下代码时:

class Base {
public:
    Base(){}
    virtual ~Base(){}
    virtual bool equals(const Base* rhs) const { return false;}
};

class DerivedA : public Base {
public:
    DerivedA() : Base(), val(0) {}
    virtual ~DerivedA() {}
    virtual bool equals(const DerivedA* rhs) const { return this->val == rhs->val;}
    int val;
};

class DerivedB : public Base {
public:
    DerivedB() : Base(), val(0) {}
    virtual ~DerivedB() {}
    virtual bool equals(const DerivedB* rhs) const { return this->val == rhs->val;}
    int val;
};

int main() {
    const DerivedA a;
    const DerivedB b;

    std::cout << a.equals(&b);
}

我明白了:

../main.cpp:104:26: error: no matching function for call to ‘DerivedA::equals(const DerivedB*) const’
std::cout << a.equals(&b);
                       ^
../main.cpp:104:26: note: candidate is:
../main.cpp:88:15: note: virtual bool DerivedA::equals(const DerivedA*) const
virtual bool equals(const DerivedA* rhs) const { return this->val == rhs->val;}
             ^
../main.cpp:88:15: note:   no known conversion for argument 1 from ‘const DerivedB*’ to ‘const DerivedA*’

但为什么它不使用基类virtual bool equals(const Base* rhs) const

1 个答案:

答案 0 :(得分:2)

bool DerivedA::equals(const DerivedA* rhs) const

不是

的覆盖
bool Base::equals(const Base* rhs) const

但是隐藏基本方法的其他重载(您可能会注意到override)。

如果您只是想取消隐藏&#39;基本方法,你可以添加

using Base::equals;

进入派生类。

但要真正解决您的问题,您必须使用多次发送。