1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class base{ public: int i,j; base(){ i=j=0; }
base(int a,int b){ i=a;j=b; } };
class derived:public base{ public: derived(int a,int b){ base(a,b); } };
int main(){ derived d(3,1); cout<<d.i<<" "<<d.j<<endl; return 0; }
|
上面的这段代码会输出什么呢?!正确的答案是输出了”0 0”. 我的理解是,虽然其中调用了base(a,b) 但是其实操作的a和b不是当前d的a,b,其实是定义了一个新的base的对象。正确的写法应该是下面这样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class base{ public: int i,j; base(){ i=j=0; } base(int a,int b){ i=a;j=b; } };
class dervied:public base{
public: derived(int a,int b):base(a,b){ } };
int main(){ derived d(3,1); cout<<d.i<<" "<<d.j<<endl; return 0; }
|