Effective C++ 学习笔记(11)
生活随笔
收集整理的這篇文章主要介紹了
Effective C++ 学习笔记(11)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
確定基類有虛析構函數
{
public:
A()
{
cout<<"A constructor"<<endl;
}
~A()
{
cout<<"A destructor"<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<"B constructor"<<endl;
}
~B()
{
cout<<"B destructor"<<endl;
}
};
int main()
{
A * p =new B();
delete p;
return 0;
}
執行結果:
對此解釋:C++語言標準規定,當通過基類指針刪除派生類的對象,而基類又沒有虛析構函數,結果是不確定的。
對此,將A的析構函數改為虛函數:
class A{
public:
A()
{
cout<<"A constructor"<<endl;
}
virtual ~A()
{
cout<<"A destructor"<<endl;
}
};
執行結果:
結果正確。
以上我們是在堆上分配的內存。
改寫main函數,在棧上分配:
int main(){
B b;
return 0;
}
結果同上。分配在棧上的對象自動調用構造函數與析構函數。
轉載于:https://www.cnblogs.com/DanielZheng/archive/2011/08/03/2126218.html
總結
以上是生活随笔為你收集整理的Effective C++ 学习笔记(11)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Winform开发中另一种样式的OutL
- 下一篇: IE6下z-index犯癫不起作用bug