2017-08-01 96 views
0

我试图编译下面的代码:为什么虚拟函数必须在超类中实现?

#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没有将它列为运行时错误,它只是说构建时错误。

+3

我想象一下,你想要纯虚函数吗? – SergeyA

+5

只是一个提示,在C++中讲一个超类是'base'类,而一个子类是'derived'类。 –

回答

5

如果你不想在所有实现基类中的虚函数,只需将其标记为纯虚:

virtual void func() = 0; 
0

不,你错了。您需要实现非虚拟功能的非。如果您不想提供实现,则需要使用= 0语法使函数变为纯虚拟。

相关问题