为什么继承的受保护构造函数不能被设为公有?

17

考虑:

class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}

为什么继承的protected构造函数不能改为public,而继承的protected成员函数可以?

2个回答

11

3

实际上,继承构造函数是可以变为公共的,但不仅仅是你所写的方式。您可以按照以下方式定义您的B类:

class B : public A {
public:
    B() {}

    B(int x) : A(x) {}  // instead of using A::A(int)
    using A::f;
};

(请在GodBolt上查看)

或许标准委员会认为,使用using A::A会有些模糊,因为基类的构造函数并不完全等同于子类的构造函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接