初始化列表不检测公开继承的成员

Initializer list doesn't detect publicly inherited member

小问题:我认为成员初始化列表的行为与使用“=”的正常初始化相同(只能使用初始化列表定义的 const 成员除外),调用待初始化对象的构造函数带有我传递的特定参数,如我在下面的示例中所示(我在其中调用值为 1 的 x 的构造函数)。但令我惊讶的是,在简单继承的情况下,编译器抱怨没有看到我试图用我的构造函数初始化的成员,尽管看到另一个用通常的 '=' 语法初始化的成员:

#include <iostream> 
using namespace std;

class A
{
public:

    int x;
    int y;
};

class B : public A
{
public:

    B() : x(1)
    {
        y = 2;
    }
};

int main()
{   
    return 0;
}

如果你 运行 上面的代码,你会看到当 y 被检测到没有问题时,你的编译器会说在 'B() : x(1)' 线。这是为什么?继承是 public,y 可以看到,没问题,为什么 x 也看不到?

我想我找到了答案:

我的对象在class A 的构造函数执行时已经初始化了一次,因此我无法在运行 B 的构造函数时重新初始化它。将 y 重新分配给值 2 是可以的,但是将 1 作为其构造函数参数传递来重新初始化 x 是编译器错误的原因。我还有什么遗漏吗???

您不能从 class B 的初始化列表中初始化 x,因为只有 class A 可以初始化它的成员。

顺便说一下,使数据成员 public 不是一个好主意。这是您的代码如何工作的示例:

#include <iostream> 
using namespace std;

class A
{
public:
    A(int x, int y) : x(x), y(y) {}
protected:

    int x;
    int y;
};

class B : public A
{
public:

    B() : A(1, 5000)
    {
        y = 2;
    }
};

int main()
{   
    return 0;
}