c++ - 虚拟公共(public)基类方法在祖先中不可见

标签 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

最佳答案

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

不是覆盖

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

但是另一个重载(正如您可能注意到的覆盖)隐藏了基本方法。

如果您只想“取消隐藏”基本方法,您可以添加

using Base::equals;

进入你的派生类。

但要真正解决您的问题,您必须使用多重调度。

关于c++ - 虚拟公共(public)基类方法在祖先中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32549514/

相关文章:

c++ - 在此函数中通过引用传递参数

c++ - 使用 zlib 压缩文件而不保存到磁盘并通过套接字发送

C++ getline();下面显示一个

c++ - 集合中的智能指针多态性

c++ - 如何将文本文件行读入 vector ?

c++ - 在 C++ 中,是否定义了通过 char* 删除基本类型(例如 uint32_t)的行为?

Java - 使用paintComponent和多态性绘制形状

c++ - 标签调度对象是否实际实例化?

c# - 多态基础

haskell - 为什么非多态类型不能在 Haskell 中实现可折叠?