【发布时间】:2017-10-29 08:04:04
【问题描述】:
这是我的代码,你也可以从http://cpp.sh/5lsds运行它
#include "iostream"
using namespace std;
class X{
private:
int c;
public:
X(){}
X(int b){
c = 11;
}
int getC();
};
class Z:public X{
public:
Z(int n){
X(23);
}
};
int main()
{
Z z(1);
cout<<z.getC()<<endl;
return 0;
}
int X::getC(){
return c;
}
我需要有X(){} 行,因为子构造函数需要调用父默认构造函数。
如果你从http://cpp.sh/5lsds 运行程序,你会看到输出是0,而我希望它是11。由于Z 构造函数使用int 参数调用X 构造函数并将c 值设置为11,但输出为0。
【问题讨论】:
-
X(23);表示创建一个临时 X,然后立即将其销毁。与*this的X子部分无关 -
如果你是从Java背景来的C++,你最好忘记这一切。
标签: c++ oop inheritance constructor initialization