【问题标题】:undefined reference to `vtable for class [duplicate]未定义对类的`vtable的引用[重复]
【发布时间】:2015-09-24 13:12:33
【问题描述】:

我从 cppfaq 12.15 获取代码并尝试编译,但在 gcc 版本 4.8.4 的 linux 中出现错误。

对 `vtable for 的未定义引用

我很惊讶,因为我没有任何虚拟方法。我已经研究了以下问题,但无法弄清楚问题。

c++ undefined reference to vtable

Undefined reference to 'vtable for xxx'

代码

#include<iostream>
#include<new>
#include<memory> using namespace std;

class Fred; typedef auto_ptr<Fred> FredPtr;

class Fred {
    public:
        static FredPtr create() throw(bad_alloc);
        static FredPtr create(int i) throw(bad_alloc);
        static FredPtr create(const Fred& x) throw(bad_alloc);
        virtual void goBowling();
    private:
        Fred(int i=10);
        Fred(const Fred& x);
        int i_;
    };

FredPtr Fred::create() throw (bad_alloc) {   return auto_ptr<Fred>(new Fred()); }

FredPtr Fred::create(int i) throw(bad_alloc) {
    return auto_ptr<Fred>(new Fred(i)); }

FredPtr Fred::create(const Fred& x) throw(bad_alloc) {
    return auto_ptr<Fred>(new Fred(x)); }

Fred::Fred(int i) {
    i_ = i;
    cout<<" This is simple constructor"<<endl; }

Fred::Fred(const Fred& x) {
    i_ = x.i_;
    cout<<" This is copy constrcutor"<<endl; }

void sample() {
    FredPtr p(Fred::create(5));
    p->goBowling(); }

int main() {
    sample();
    return 0; }

错误:

/tmp/cc6JnLMO.o: In function `Fred::Fred(int)':
cpp12_15.cpp:(.text+0x204): undefined reference to `vtable for Fred'
/tmp/cc6JnLMO.o: In function `Fred::Fred(Fred const&)':
cpp12_15.cpp:(.text+0x247): undefined reference to `vtable for Fred'
collect2: error: ld returned 1 exit status 

【问题讨论】:

  • cplusplus.com/reference/memory/auto_ptr - 请参阅已弃用说明
  • 你应该定义一个public: virtual ~Fred() {}析构函数。
  • 通常这个错误意味着你忘记包含其他函数的函数体
  • 缺少void Fred::goBowling() {} 的定义。
  • 你说你没有虚函数,你却有virtual void goBowling();....

标签: c++


【解决方案1】:

只要你的类定义中有一个 virtual 关键字,即使你没有从它继承,编译器也会静态构建 vtable,正如你在你的类中看到的那样,你没有定义你的 goBowling 方法,所以编译会失败。

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2011-07-27
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多