C++ link error : undefined reference to 'vtable for ...'
2016-06-30 10:06
531 查看
今天在做一道C++继承多态的练习的时候遇到了一个错误,代码如下:
错误:
原因是因为,在写C++多态的时候,基类的虚函数没有函数体。
有一篇博客这样提到:
“链接器linker需要将虚函数表vtable 放入某个object file,但是linker无法找到正确的object文件。这个错误常见于刚刚创建一系列有继承关系的class的时候,这个时候很容易忘了给base class的virtual function加上函数实现。”
博客链接
#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加上函数实现。”
博客链接
相关文章推荐
- vc和MFC的详细历史
- C++ 11 auto关键字
- C语言不定长数组及初始化
- 300. Longest Increasing Subsequence(C++实现)
- DES加密解密C/C++
- C++中this指针的理解和用法
- 站在巨人的肩膀上,C++开源库大全
- STM32开发C语言---switch
- C,C++表达式中含++的求值顺序
- 一起talk C栗子吧(第一百六十八回:C语言实例--C语言中的布尔--bool类型)
- 彻底搞定C语言指针详解-完整版-时候初学者-必备
- STM32开发C语言基础知识---关键字volatile
- C++中两种计算时间方法的比较
- C++异常处理: try,catch,throw,finally的用法
- C++如何声明类成员函数指针或类成员变量指针(A::*)
- c++银行家算法
- 名字修饰约定extern "C"与extern "C++"浅析
- 关于__stdcall和__cdecl调用方式的理解
- 类与对象
- 【读书笔记】【C++】类外访问私有数据成员的两种方式