加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么派生类必须重新定义覆盖的基类方法

发布时间:2020-12-16 09:43:19 所属栏目:百科 来源:网络整理
导读:参见英文答案 C++ override/overload problem????????????????????????????????????1个 我不明白为什么我需要重新定义一个覆盖的基类方法. 在这里,如果我在派生类中注释foo()方法,它就不会编译. 谢谢你的解释. class Base {public: void foo() { }};class De
参见英文答案 > C++ override/overload problem????????????????????????????????????1个
我不明白为什么我需要重新定义一个覆盖的基类方法.

在这里,如果我在派生类中注释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);
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读