今天突然想到基类子类含有同名变量的时候,编译器是怎么区分谁是谁的呢,于是写了段代码测了下.
1 #include "stdio.h" 2 3 class Base 4 { 5 public: 6 Base():m(1) 7 { 8 9 } 10 public: 11 int m; 12 }; 13 14 class Inherit:public Base 15 { 16 public: 17 Inherit():m(2) 18 { 19 20 } 21 public: 22 int m; 23 }; 24 25 int main() 26 { 27 Inherit tmp; 28 tmp.m = 3; 29 Base* pBase = &tmp; 30 Inherit* p = &tmp; 31 32 printf("%d,%d,%d,%d,%d",tmp.m,tmp.Base::m,pBase->m,p->Base::m,p->m); 33 34 return 0; 35 };
输出结果:3,1,1,1,3
可以看出,当基类A与子类B含同名变量name时,通过B.name或是指向子类的指针pB,pB->name时,取到的都是子类的值.如果想取到基类的值要这样B.A::name或pB->A::name