c++ - 为什么派生类必须重新定义重写的基类方法

标签 c++

<分区>

我不明白为什么我需要重新定义一个覆盖的基类方法。

在这里,如果我在派生类中注释 foo() 方法,它不会编译。

感谢您的解释。

class Base {
public:
    void foo() {
    }
};

class Derived: public Base {
public:
#define compile_ok
#ifdef compile_ok
    // if this method is commented, it does not compile
    void foo() {
        Base::foo();
    }
#endif
    void foo(int i) {
    }
    void test() {
        foo();
        foo(1);
    }
};

void testOverride() {
    Derived d;
    d.test();
}

最佳答案

您对 foo 的声明采用单个 int 参数将隐藏 Base 中所有名为 foo 的函数。您可以像这样从 Base 中获取一个隐藏名称:

class Derived: public Base {
public:
    using Base::foo; // Pulls foo from Base
    void foo(int i) {
    }
    void test() {
        foo();
        foo(1);
    }
};

关于c++ - 为什么派生类必须重新定义重写的基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499146/

相关文章:

c++ - 将 const QByteArray 传递给重载函数

c++ - enable_if 和转换运算符?

c++ - 蓝牙服务问题

c++ - 检查一个字节中 ON 的位数?

c++ - 为什么我的复制构造函数在这种情况下只被调用两次?

c++ - C++中的静态结构和静态全局变量

c++ - 如何用 C++ 编写一个简单的类?

c++ - 我应该覆盖哪些运算符以便比较两个 vector ?

c++ - "class::data member is private"错误,但我正在使用成员函数对其进行操作?

c++ - 对抽象类和 `decltype` 的左值引用