(1)
class A
{
public:
~A(){cout<<"A destruction"<<endl;}
};
class B:public A
{
public:
~B(){cout<<"B destruction"<<endl;}
};
int main()
{
B *p = new B;
delete p;
return 0;
}
输出:
B destruction
A destruction
(2)
class A
{
public:
virtual ~A(){cout<<"A destruction"<<endl;}
};
class B:public A
{
public:
int x;
virtual ~B(){cout<<"B destruction"<<endl;}
};
void Test()
{
A *p = new A;
}
int main()
{
A *p = new B;
delete p;
return 0;
}
B destruction
A destruction
(3)
class A
{
public:
~A(){cout<<"A destruction"<<endl;}
};
class B:public A
{
public:
int x;
~B(){cout<<"B destruction"<<endl;}
};
void Test()
{
A *p = new A;
}
int main()
{
A *p = new B;
//只释放了基类所占用的空间,x所占用的空间没有释放
{
public:
~A(){cout<<"A destruction"<<endl;}
};
class B:public A
{
public:
int x;
~B(){cout<<"B destruction"<<endl;}
};
void Test()
{
A *p = new A;
}
int main()
{
A *p = new B;
//只释放了基类所占用的空间,x所占用的空间没有释放
delete p; //内存泄露
return 0;
}
return 0;
}
输出:
A destruction