這是我的代碼,你也可以從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子部分。 –