gpt4 book ai didi

c++ - C++中从虚析构函数调用虚方法

转载 作者:行者123 更新时间:2023-11-30 01:08:23 25 4
gpt4 key购买 nike

<分区>

我想销毁 B 类的对象。

class A {
public:
A() {
std::cout << "construct A" << av::endl;
a = new int;
}
virtual ~A() {
std::cout << "destruct A" << av::endl;
this->clear();
}
virtual void clear() {
std::cout << "clear A" << av::endl;
delete a;
}
protected:
int *a;
};

class B : public A {
public:
B() {
std::cout << "construct B" << av::endl;
b = new int;
}
~B() {
std::cout << "destruct B" << av::endl;
}
void clear() override {
std::cout << "clear B" << av::endl;
delete b;
delete this->a;
}
private:
int *b;
};

我希望使用 clear() 方法来完成。但是当我执行以下代码时:

A *a = new B();
delete a;

我得到:

construct A construct B destruct B destruct A clear A

clear B 永远不会被打印出来。我做错了什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com