繁体   English   中英

在派生 class 中显式调用基类 class 构造函数

[英]Explicitly calling base class constructor in derived class

请问是否可以在derived class中显式调用base class构造函数? (如果不是,为什么?)

我问这个问题是因为我写了下面的玩具代码,结果让我很困惑:

class X
{
public:
    void wow()
    {
        cout << "wow\n";
    }
protected:
    X()
    {
        cout << "creating X\n";
    }
    X(int i)
    {
        cout << "creating X with i\n";
    }
};

class Y : protected X
{
public:
    X r = X{ 1 };  // error at this line: (C2248) 'X::X': cannot access protected member declared in class 'X'
};

int main()
{
    Y y;
    y.r.wow();
}

但是,如果我在class Y中稍作修改,代码实际上可以编译:

// X defined same as above...

class Y : protected X
{
public:
    X r = { 1 };
};

int main()
{
    Y y;        // creating X
                // creating X with i
    y.r.wow();  // wow
}

我正在使用 Visual Studio 2022。

Inheritance 不提供protected的完全访问权限,您只能通过派生的 class 访问受保护的字段。因此您无法为您的成员访问受保护的字段。 更详细的见

受保护的成员访问

class的受保护成员只能访问

[..]

  1. 到该 class 的任何派生 class 的成员和朋友(C++17 之前),但仅当访问受保护成员的 object 的 class 是派生 class 的派生 class 或派生的 8839811829195189 的派生 8839811829195189 时

第二个样本也应该出于同样的原因而失败(实际上是为 clang/gcc Demo做的)。 我会说 msvc 错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM