1、父类指针获取子类成员变量
1 #include <iostream> 2 3 using namespace std; 4 5 class Base { 6 public: 7 virtual void get() {} 8 }; 9 10 class Derive :public Base 11 { 12 public: 13 Derive(){} 14 void get() { 15 printf("The third element is %d ", _x[2]); 16 }; 17 int _x[6] = { 0,1,2,3,4,5 }; 18 }; 19 20 int main() 21 { 22 Base *base = new Derive(); 23 base->get(); 24 25 return 0; 26 }
2、类型转换
1 #include <iostream> 2 3 using namespace std; 4 5 class Base 6 { 7 public: 8 void virtual Func() 9 { 10 cout << "Base "; 11 } 12 }; 13 14 class Derived : public Base 15 { 16 public: 17 void Func() 18 { 19 cout << "Derived "; 20 } 21 22 void NewFunc() 23 { 24 cout << "New func "; 25 } 26 int x[5] = { 0,1,2,3,4 }; 27 }; 28 29 int main() 30 { 31 Base* b = new Derived(); 32 b->Func(); 33 34 Derived* d =dynamic_cast<Derived*>(b) ; 35 // 不安全的转换 36 //Derived* d = (Derived*)b; 37 d->NewFunc(); 38 cout << d->x[2] << endl; 39 40 return 0; 41 }