这是我试图理解输出的代码.
class A
{
public:
A();
~A(){ cout<<"Destructor Called from A"<<endl;}
A(int x):Z(x){ cout<<"Constructor Called from A"<<endl; };
private:
int Z;
};
class B:public A
{
public:
B();
~B(){ cout<<"Destructor Called from B"<<endl;}
B(int x):A(x),Y(x){ cout<<"Constructor Called from B"<<endl; };
private:
int Y;
};
int main() {
A *a = new B(10);
delete a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为此,我得到了输出
Constructor Called from A
Constructor Called from B
Destructor Called from A
Run Code Online (Sandbox Code Playgroud)
我的问题是,类的析构函数发生了什么B?对象切片是否在这里起作用?
您需要使超类的析构函数为虚拟:
class A {
virtual ~A(){ cout<<"Destructor Called from A"<<endl;}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |