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

今天在做一道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;
}

错误:

link error

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

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

博客链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值