父类指针访问子类成员变量
生活随笔
收集整理的這篇文章主要介紹了
父类指针访问子类成员变量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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\n", _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\n"; 11 } 12 }; 13 14 class Derived : public Base 15 { 16 public: 17 void Func() 18 { 19 cout << "Derived\n"; 20 } 21 22 void NewFunc() 23 { 24 cout << "New func\n"; 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 }?
轉載于:https://www.cnblogs.com/xidian2014/p/8507788.html
總結
以上是生活随笔為你收集整理的父类指针访问子类成员变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spark:如何替换sc.paralle
- 下一篇: BZOJ 1293 [SCOI2009]