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

标签 c++ gcc g++ virtual-functions

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

相关文章:

c++ - 捕获 boost 线程中断和退出线程的正确方法

c++ - 如何删除指针的 STL 列表?

c++ - 如何修复 "reference cannot be bound to dereferenced null pointer"警告

c - 是否(不)可以在 C 源代码中使用特殊字符?

gcc - 无法配置 gcc - 找不到 mpfr

c++ - BOOST_STATIC_ASSERT_MSG - 缺少错误信息

c++ - 编译c++文件时出错: Undefined symbols

c++ - 处理作用域变量的内部函数

c++ - 未使用的析构函数会被优化掉吗?

c++ - g++ 中包含哪些库?