gpt4 book ai didi

c++ - undefined reference to vtable 错误是由现代 g++ 编译器解决的吗?

转载 作者:太空狗 更新时间:2023-10-29 20:12:16 24 4
gpt4 key购买 nike

根据 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com