您的位置:首页 > 编程语言 > C语言/C++

C++ link error : undefined reference to 'vtable for ...'

2016-06-30 10:06 531 查看
今天在做一道C++继承多态的练习的时候遇到了一个错误,代码如下:

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

class Pet
{
protected:
string name;
int length;
int weight;
int current;
public:
Pet(string s = "", int a = 0, int b = 0, int c = 0):name(s), length(a),
weight(b), current(c){};
virtual void display(int day);
};

class Cat : public Pet
{
public:
Cat(string s = "", int a = 0, int b = 0, int c = 0):Pet(s, a, b, c){};
virtual void display(int day);
};

void Cat::display(int day)
{
length += (day - current) * 1;
weight += (day - current) * 2;

cout << name << " " << length << " " << weight << " " << endl;
}

class Dog : public Pet
{
public:
Dog(string s = "", int a = 0, int b = 0, int c = 0):Pet(s, a, b, c){};
virtual void display(int day);
};

void Dog::display(int day)
{
length += (day - current) * 2;
weight += (day - current) * 1;

cout << name << " " << length << " " << weight << " " << endl;
}

int main()
{
Pet *pt[10];
int ope;
int t;
int tot = 0;

while(cin >> ope)
{
if(ope > 10)
{
t = ope;
break;
}

string name;
int w, h, d;

if(ope == 1)
{
cin >> name >> w >> h >> d;
pt[tot ++] = new Cat(name, w, h, d);
}
else if(ope == 2)
{
cin >> name >> w >> h >> d;
pt[tot ++] = new Dog(name, w, h, d);
}
}

for(int i = 0; i < tot; i++)
{
pt[i] -> display(t);
}

return 0;
}


错误:



原因是因为,在写C++多态的时候,基类的虚函数没有函数体。

有一篇博客这样提到:

“链接器linker需要将虚函数表vtable 放入某个object file,但是linker无法找到正确的object文件。这个错误常见于刚刚创建一系列有继承关系的class的时候,这个时候很容易忘了给base class的virtual function加上函数实现。”

博客链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: