我正在尝试编译以下代码:
#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/