c++ - 为什么必须在父类(super class)中实现虚函数?

标签 c++ xcode c++11

我正在尝试编译以下代码:

#include <iostream>
class X{
public:
    virtual void func();
};
class Y : public X{
public:
    virtual void func(){
        std::cout << "y" << std::endl;
    }
};
int main(){
    Y* y = new Y();
    y->func();
    return 0;
}

但构建失败(在 Xcode - C++11 上)并显示以下消息:

Undefined symbols for architecture x86_64:
  "typeinfo for X", referenced from:
      typeinfo for Y in c.o
  "vtable for X", referenced from:
      X::() in c.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

但是,只要我在 X 中添加 func 的实现,它就会成功构建。我很确定,虚拟方法是可选的,可以在父类(super class)中实现,但我不明白为什么会这样。另外,如果在 main() 中注释代码,它会成功构建。我假设问题是在 main 中调用 func(),但 Xcode 没有将其列为运行时错误,它只显示构建时错误。

最佳答案

如果根本不想在基类中实现虚函数,只需将其标记为纯虚函数即可:

virtual void func() = 0;

关于c++ - 为什么必须在父类(super class)中实现虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45446433/

相关文章:

c++ - 在虚幻引擎 C++ 中设置计时器

c++ - 转换 char* 时的不同值

iphone - Xcode - 获取所有方法头的列表

c++ - const 整数模板参数的条件

c++ - 即使调用 get() , future 也不会运行

c++ - 仅将 const 引用绑定(bind)到 const 值

c++ - 不使用new()可以实现工厂模式构造吗?

c++ - new 表达式中详细类型说明符的条件表达式解析错误

iphone - 如何在我的 iPhone 应用程序中提取网站的 HTML 源代码?

objective-c - 如何使用 Mac 在 Finder 中的文件夹树前面添加复选框?