C++ 编译报错 undefined reference to “vtable for child”

先说结果: 父类定义的虚函数,子类如果重载了 ,那就必须定义具体实现,不能弄个没有函数体的函数名放那里碰瓷。 


 
 
  1. #include<iostream>
  2. using namespace std;
  3. class parent
  4. {
  5. public:
  6. parent(){
  7. std:: cout<< "parent constructor no param"<< std:: endl;
  8. };
  9. private:
  10. parent( int a){
  11. std:: cout<< "parent constructor: "<<a<< std:: endl;
  12. };
  13. public:
  14. virtual ~parent(){
  15. std:: cout<< "parent disconstructor~"<< std:: endl;
  16. };
  17. virtual void opt(){
  18. std:: cout<< "parent opt"<< std:: endl;
  19. };
  20. };
  21. class child: public parent
  22. {
  23. public:
  24. child( int a){
  25. cout<< "child constructor: "<<a<< endl;
  26. };
  27. ~child();
  28. void opt(){
  29. std:: cout<< "child opt"<< std:: endl;
  30. };
  31. void child_do(){
  32. std:: cout<< "child do"<< std:: endl;
  33. };
  34. };
  35. int main()
  36. {
  37. int b = 10;
  38. parent* test = new child(b);
  39. test->opt();
  40. reinterpret_cast<child*>(test)->child_do();
  41. delete parent;
  42. return 0;
  43. }

 
 
  1. /tmp/cc3sxtLw.o: In function `child::child(int) ':
  2. test.cpp:(. text._ZN5childC2Ei[_ZN5childC5Ei]+ 0x1d): undefined reference to `vtable for child '

找了好一会,发现是子类的析构函数只是声明了,没有定义,

改成 ~child(){}; 定义上就好了。

但是我记得之前也有过忘记定义析构函数具体内容的情况,编译并没有报错,

于是回过头注意到 这句报错的含义好像并不是说子类的析构函数没有定义,

undefined reference to `vtable for child' -> 对child的虚表未定义的引用,

这里 vtable 应该就是指的虚函数表,

尝试着换一种方式修改 ~child(); 这个不变, 把 virtual ~parent 改为 ~parent,

果然 也不报错了,但是我们都知道这样改的后果是啥,就是父类指针指向的子类对象析构不会调用子类的析构函数了。


 
 
  1. [root@iZuf6iemoke3l0asocwqo5Z 继承]# ./a. out
  2. parent constructor no param
  3. child constructor: 10
  4. child opt
  5. child do
  6. parent disconstructor~
  7. [root@iZuf6iemoke3l0asocwqo5Z 继承]#

所以,老老实实给父类的析构函数加上 virtual, 然后完善对子类析构函数的定义.


 
 
  1. virtual ~parent(){
  2. std:: cout<< "parent disconstructor~"<< std:: endl;
  3. };
  4. ~child(){
  5. cout<< "child disconstructor"<< endl;
  6. };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值