#include <iostream>
using namesapce std;
class A
{
public:
virtual ~A(){cout<<"delete A"<<endl};
};
class B: public A
{
public:
B(int n):n(n){}
void show(){cout<<n<<endl;}
~B(){cout<<"delete B"<<endl;}
private:
int n;
}
int main()
{
A *pa;
B *pb = new B(1);
pa = pb;
delete pa;
pb->show();
return 0;
}
當CALSS A的析構函數是virtual ~A(){...}
,程序的輸出: delete B delete A 1
當類A的析構函數是~A(){...}
,progarm的輸出: delete A 0
爲什麼n的值是不同的時,類A的析構函數是虛擬或非虛擬?當調用B的析構函數銷燬對象時,爲什麼會話成員n仍然存在?當A類的析構函數是虛擬的還是非虛擬的時,爲什麼B的calss成員n有不同的值?
你明白虛擬函數是什麼嗎? – Barry
什麼是'pb-> show(){};'? – AnT
你可能想閱讀這個http://www.learncpp.com/cpp-tutorial/122-virtual-functions/ –