【问题标题】:Why is the destructor of the inherited class not called? [duplicate]为什么不调用继承类的析构函数? [复制]
【发布时间】:2021-03-20 10:50:42
【问题描述】:

为什么不调用Circle析构函数?

#include "stdafx.h"
#include <iostream>

class Shape { 
public:
    Shape() { 
        std::cout << "Shape Constructor\n"; 
    };
    ~Shape() { 
        std::cout << "Shape Destructor\n"; 
    };
};

class Circle: public Shape {
public:
    Circle() { 
        std::cout << "Circle Constructor\n"; 
    };
    ~Circle() { 
        std::cout << "Circle Destructor\n"; 
    };
};

int _tmain(int argc, _TCHAR* argv[])
{
    Shape *object;  
    object = new Circle(); 
    delete object;
    return 0;
}

输出:

Shape Constructor
Circle Constructor
Shape Destructor

【问题讨论】:

  • 因为(基类的)析构函数不是virtual
  • 在发布之前,请尽量减少您的示例。

标签: c++


【解决方案1】:

默认情况下,继承不允许派生类析构函数自动调用基类的析构函数。但是将基类的析构函数定义为virtual 可以使派生类在销毁之前隐式调用基类的析构函数。

【讨论】:

  • 只是措辞问题,但反过来:delete object 仅调用基类析构函数。 “不允许您的派生类析构函数自动调用基类的析构函数”virtual 也不会发生这种情况
  • 这个答案只是部分正确。在基类中没有虚拟析构函数,delete 表达式具有未定义的行为。虽然在实践中相当普遍(即有几个编译器的情况)结果只是调用基类构造函数,但这不是标准所要求的。
猜你喜欢
  • 2012-01-29
  • 2021-06-21
  • 2012-12-09
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多