根据 this必须定义虚函数,否则链接器会提示并报告错误“未定义对 vtable 的引用”,但为什么不 ideone编译器给出以下代码的任何错误?
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"test() is called\n";
}
virtual void test();
};
int main() {
Test t;
// your code goes here
return 0;
}
最佳答案
您没有正确阅读文档。相关段落的第一句话说:
The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined, but does not require any diagnostic for violations of this rule [class.virtual]/8.
因此,预计您可能不会收到错误,尤其是因为您实际上并未调用 test()
(尽管构造函数的输出中存在谎言)。
实际上,只有在以下情况下,您才可能得到此诊断:
- 你调用了一个你没有定义的虚函数
- 你实例化了一个你没有定义其
virtual
析构函数的对象
但请不要误会:无论如何,您的程序都有未定义的行为。
关于c++ - undefined reference to vtable 错误是由现代 g++ 编译器解决的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28675062/