基类中的虚函数可以隐藏吗?

时间:2015-12-13 04:41:10

标签: c++

我在http://en.cppreference.com/w/cpp/language/virtual中的'详细'下运行了第一个示例来证明这个想法

  

Base :: vf不需要是可见的(可以声明为private,或   继承使用私有继承)被覆盖。

class B {
    virtual void do_f(); // private member
 public:
    void f() { do_f(); }; // public interface
};
struct D : public B {
    void do_f() override; // overrides B::f
};

int main()
{
    D d;
    B* bp = &d;
    bp->f(); // calls D::do_f();
}

但编译器报告错误:http://cpp.sh/5hk6v

/tmp/ccNhIT1Y.o: In function `main':
:(.text.startup+0xb): undefined reference to `vtable for D'
:(.text.startup+0x10): undefined reference to `D::do_f()'
collect2: error: ld returned 1 exit status

(我选择了C ++ 14)

声明错误或代码中是否有错误?

1 个答案:

答案 0 :(得分:2)

您发布的链接更多的是概念示例,而不是完整的可随时构建的代码。

您声明D::do_f但无处可定义。添加至少一个空体,它将构建没有错误。 (如@ Peter的评论中所述,列出的错误实际上来自链接器,而不是编译器。)

struct D : public B {
    void do_f() override {} // overrides B::f
};