为什么不调用派生的 class 析构函数?
Why isn't the derived class destructor being called?
我正在使用指向派生 类 的指针进行一些练习,当我 运行 下面提供的代码时,我得到的输出是
Constructor A
Constructor B
Destructor A
有人能告诉我为什么 B::~B() 在这里没有被调用吗?
class A {
public:
A() { std::cout << "Constructor A\n"; }
~A() { std::cout << "Destructor A\n"; }
};
class B : public A {
public:
B() { std::cout << "Constructor B\n"; }
~B() { std::cout << "Destructor B\n"; }
};
int main() {
A* a = new B;
delete a;
}
因为覆盖的方法需要是虚拟的
class A{
public:
A()
{
std::cout<<"Constructor A\n";
}
virtual ~A()
{
std::cout<<"Destructor A\n";
}
};
class B : public A{
public:
B()
{
std::cout<<"Constructor B\n";
}
virtual ~B()
{
std::cout<<"Destructor B\n";
}
};
指针a
的静态类型是A *
。
A* a = new B;
因此在class A
.
中搜索所有使用该指针的被调用成员函数
要调用指针的动态类型的析构函数,即class B
,需要在class中将析构函数声明为virtual
A
。例如:
#include <iostream>
class A {
public:
A() { std::cout << "Constructor A\n"; }
virtual ~A() { std::cout << "Destructor A\n"; }
};
class B : public A {
public:
B() { std::cout << "Constructor B\n"; }
~B() override { std::cout << "Destructor B\n"; }
};
int main() {
A* a = new B;
delete a;
}
我正在使用指向派生 类 的指针进行一些练习,当我 运行 下面提供的代码时,我得到的输出是
Constructor A
Constructor B
Destructor A
有人能告诉我为什么 B::~B() 在这里没有被调用吗?
class A {
public:
A() { std::cout << "Constructor A\n"; }
~A() { std::cout << "Destructor A\n"; }
};
class B : public A {
public:
B() { std::cout << "Constructor B\n"; }
~B() { std::cout << "Destructor B\n"; }
};
int main() {
A* a = new B;
delete a;
}
因为覆盖的方法需要是虚拟的
class A{
public:
A()
{
std::cout<<"Constructor A\n";
}
virtual ~A()
{
std::cout<<"Destructor A\n";
}
};
class B : public A{
public:
B()
{
std::cout<<"Constructor B\n";
}
virtual ~B()
{
std::cout<<"Destructor B\n";
}
};
指针a
的静态类型是A *
。
A* a = new B;
因此在class A
.
要调用指针的动态类型的析构函数,即class B
,需要在class中将析构函数声明为virtual
A
。例如:
#include <iostream>
class A {
public:
A() { std::cout << "Constructor A\n"; }
virtual ~A() { std::cout << "Destructor A\n"; }
};
class B : public A {
public:
B() { std::cout << "Constructor B\n"; }
~B() override { std::cout << "Destructor B\n"; }
};
int main() {
A* a = new B;
delete a;
}