1 #include<iostream> 2 using namespace std; 3 4 struct IA 5 { 6 virtual void funInIA() = 0; 7 }; 8 9 struct IB 10 { 11 virtual void funInIB() = 0; 12 }; 13 14 struct C : public IA, public IB 15 { 16 virtual void funInIA() 17 { 18 cout << "funInIA" << endl; 19 } 20 21 virtual void funInIB() 22 { 23 cout << "funInIB" << endl; 24 } 25 }; 26 27 int main() 28 { 29 IA* pIA = new C; 30 pIA->funInIA(); 31 32 IB* pIB = (IB*)(void*)(pIA); 33 //IB* pIB = new C; 34 pIB->funInIB(); 35 36 delete pIA; 37 return 0; 38 }
上面代码输出:(偏移,欺骗,误打误撞)
funInIA
funInIA
如果将Line 23换成:
IB* pIB = (IB*)(C*)(pIA);
or
IB* pIB = dynamic_cast<IB*>(pIA);
so 代码输出:
funInIA
funInIB
如果,代码如下:
1 #include<iostream> 2 using namespace std; 3 4 struct IA 5 { 6 virtual void funInIA() = 0; 7 }; 8 9 struct IB 10 { 11 virtual void funInIB() = 0; 12 }; 13 14 struct C : public IA, public IB 15 { 16 virtual void funInIA() 17 { 18 cout << "C - funInIA" << endl; 19 } 20 21 virtual void funInIB() 22 { 23 cout << "C - funInIB" << endl; 24 } 25 }; 26 27 28 struct D : public IA, public IB 29 { 30 virtual void funInIA() 31 { 32 cout << "D - funInIA" << endl; 33 } 34 35 virtual void funInIB() 36 { 37 cout << "D - funInIB" << endl; 38 } 39 }; 40 41 IA* CreateInstance() 42 { 43 return new C; 44 //or //return new D; 45 } 46 47 int main() 48 { 49 IA* pIA = CreateInstance(); 50 pIA->funInIA(); 51 52 IB* pIB = (IB*)(pIA); 53 pIB->funInIB(); 54 55 delete pIA; 56 return 0; 57 }
以上输出:
C - funInIA C - funInIA
无论将代码line 52 改成
IB* pIB = (IB*)(D*)(pIA);
or
IB* pIB = (IB*)(C*)(pIA);
代码都会输出:
C - funInIA C - funInIB
如果子类重新了父类函数,又想调用父类,则可以:
Derive-Instance.Base::print();
1 没有虚析构函数,继承类没有析构 2 //Example: non- virtual destructors for dynamically allocated objects. 3 4 #include <iostream.h> 5 #include <string.h> 6 class Thing 7 { public: 8 virtual void what_Am_I( ) {cout << "I am a Thing. ";} 9 ~Thing(){cout<<"Thing destructor"<<endl;} 10 }; 11 class Animal : public Thing 12 { 13 public: 14 virtual void what_Am_I( ) {cout << "I am an Animal. ";} 15 ~Animal(){cout<<"Animal destructor"<<endl;} 16 }; 17 int main( ) 18 { 19 Thing *t =new Thing; 20 Animal*x = new Animal; 21 Thing* array[2]; 22 array[0] = t; // base pointer 23 array[1] = x; 24 for (int i=0; i<2; i++) array[i]->what_Am_I( ) ; 25 delete array[0]; 26 delete array[1]; 27 return 0; 28 }
以上代码输出:
I am a Thing. I am an Animal. Thing destructor Thing destructor
当把父类析构函数加上virtual后,以上代码输出:
I am a Thing. I am an Animal. Thing destructor Animal destructor Thing destructor