请问下如下代码为何输出的是:0,0,而不是3,1?
我的理解是先构造父类,此刻i=j=0, 然后在构造子类的时候,调用父类的构造函数 Base(3, 1)的时候把3,1赋值给继承来的i,j, 最后输出的d.i,d.j应该是3,1。但是实际却不是。
class Base {
public:
int i;
int j;
Base () {
i = j = 0;
}
Base (int a, int b) {
i = a;
j = b;
}
};
class Derive:public Base {
public:
Derive (int a, int b) {
Base(a, b);
}
};
int main(){
Derive d(3,1);
cout << d.i << "," << d.j << endl; //输出是: 0,0
return 0;
}
###class Derive: public Base {
public:
Derive(int a, int b): Base(a, b) {
// 调用父类构造要像上面这么写
// Base(a, b) 是产生了一个局部对象,而不是调用父类构造
}
};
###Derive (int a, int b) {
Base(a, b);
}
这里的 Base(a, b)
只是定义了一个 Base 类型的临时变量,说不定在编译期优化后,这条语句直接变成了,
Derive (int a, int b) {
// 没掉了这里
}
我猜你是弄混了构造函数初始化列表,你想要的是这个,
Derive (int a, int b) : Base(a, b) {
}