gpt4 book ai didi

c++ - 父类中的构造函数未将值分配给私有(private)变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:01 25 4
gpt4 key购买 nike

这是我的代码,您也可以从 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

最佳答案

你应该使用 member initializer list ,

In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members.

例如

Z(int n) : X(23) {}

I need to have X(){} line since the child constructor needs to call the parent default constructor.

有了成员初始化器列表,就不再需要它了(在此代码示例中)。

对于 X(23); 在构造函数的主体中,您只是创建一个临时的 X,它与基础子对象 无关Z 的>X;然后 X 的默认构造函数(即 X::X())将用于它。即它等同于:

Z(int n) : X() {  // initialize the base suboject X via X::X()
X(23); // create an unnamed temporary via X::X(int)
}

关于c++ - 父类中的构造函数未将值分配给私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44235262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com