类是否可以在其构造函数的参数中设置它从另一个类继承的变量的值

Is it possible for a class to set the value of a variable that it inherited from another class in the parameter of its constructor?

本文关键字:另一个 变量 继承 设置 参数 是否 构造函数      更新时间:2023-10-16

A包含受保护的int x。类 B 扩展类A 。现在,类B要做的是将x的值设置为其自己的构造函数中的传递参数。当我尝试这样做时,我收到错误:

"x" 不是类 "B" 的非静态数据成员或基类。

#include <string>
#include <iostream>
class A {
protected:
    int x;
public:
    A()
    {
    }
};
class B : public A {
public:
    B(int x)
        : x(x)
    {
    }
};
int main()
{
}

您可以"设置"它,但不能初始化它,因为在初始化基类对象时它已经初始化了。您可以像这样"设置"它:

B(int x) 
{ 
    this->x = x; // assignment, not initialization
}

对于A的一个构造函数来说,处理A::x的初始化会更有意义:

A(int x) : x(x) {}

然后在B中使用它:

using A::A; // allows B b{42};