我在玩弄一些C++的未來,並進入了一些令我感興趣的東西。C++ inheritance
class Base
{
public:
Base(){ cout<<"C: Base"<<endl;}
~Base(){ cout<<"D : Base"<<endl;}
};
class Derived: public Base
{
public:
Derived(){ cout<<"C: Derived"<<endl;}
~Derived(){ cout<<"D : Derived"<<endl;}
};
class Derived2: public Derived
{
public:
Derived2(){ cout<<"C: Derived2"<<endl;}
~Derived2(){ cout<<"D : Derived2"<<endl;}
};
class Derived3: public Derived2
{
public:
Derived3(){ cout<<"C: Derived3"<<endl;}
~Derived3(){ cout<<"D : Derived3"<<endl;}
};
void main()
{
Derived *Var = new Derived2();
delete (Derived3*)Var; //<---- this should cause some type of run-time error
}
爲什麼上面不會產生錯誤。是否因爲Derived3中沒有數據要發佈?或者我錯過了什麼?
而是將其輸出
C: Base
C: Derived
C: Derived2
D : Derived3 <--- SHOULD NOT BE POSSIBLE
D : Derived2
D : Derived
D : Base
也許它不會被稱爲運行時錯誤,但如果你真的調皮的話,會終止你的位置...... – Jon 2011-04-01 00:34:51
@Jon:你說得對。我更新了我的答案。謝謝。 – AnT 2011-04-01 00:40:29