我試圖編譯下面的代碼:爲什麼虛擬函數必須在超類中實現?
#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,它會成功構建。我很確定,這個虛擬方法是可選的,可以在超類中實現,但我不明白爲什麼會發生這種情況。另外,如果在main()中註釋代碼,它會成功建立。我假設問題是在main中調用func(),但Xcode沒有將它列爲運行時錯誤,它只是說構建時錯誤。
我想象一下,你想要純虛函數嗎? – SergeyA
只是一個提示,在C++中講一個超類是'base'類,而一個子類是'derived'類。 –