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

标签 c++ oop inheritance constructor initialization

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

相关文章:

javascript - 如何以OOP方式处理Textbox事件?

html - 覆盖 <html> 元素样式

c++ - 关于 C++ 中自定义对象的构造函数/析构函数和新建/删除运算符

c++ - 如何使用 C++ 获取路径的文件和目录列表?

C++:从父级调用子级静态方法

C++ 实现抽象类

java - Java中的继承,访问子方法并使用父类数组

c++ - 为什么无符号和有符号相减后符号不同?

c# - 覆盖显式接口(interface)实现?

database-design - 关系数据库中的空值可以吗?