c++ 子类要正确的调用父类构造函数
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的对象。正确的写法应该是下面这样
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; }
转载: https://xtestw.com/2015/04/05/cplusplus/#more