这是我的代码,你也可以从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
构造函数调用构造函数X
与int
参数,并将其设置c
值11
但输出0
。
'X(23);'装置来创建临时X,然后将其立即销毁。它无关的'* this' –
如果您来从Java背景的C++,你最好都忘了的X子部分。 –