c++ 11继承构造函数和访问修饰符

时间:2022-09-02 10:05:23

Assuming the following layout:

假设以下布局:

class Base
{
protected:
    Base(P1 p1, P2 p2, P3 p3);

public:
    virtual void SomeMethod() = 0;
}

class Derived : public Base
{
public:
    using Base::Base;

public:
    virtual void SomeMethod() override;
};

Should I be able to specify Derived's constructor as public here? VC++ gives the following error:

我应该能够在这里指定派生的构造函数吗?vc++给出了以下错误:

cannot access protected member declared in class 'Derived'
compiler has generated 'Derived::Derived' here [points to the using Base::Base line]
see declaration of 'Derived'

无法访问'派生'编译器生成'派生:派生'类中声明的受保护成员,这里[指向使用基:基线]请参见'派生'声明

i.e. it's ignoring the access modifier above the inherited constructor.

也就是说,它忽略了继承构造函数上面的访问修饰符。

Is this a limitation of the feature? It doesn't make any sense for the Base class to have a public constructor, as it can never be instantiated directly (due to the pure virtual method).

这是特性的限制吗?基类拥有公共构造函数没有任何意义,因为它永远不会被直接实例化(由于纯粹的虚拟方法)。

1 个解决方案

#1


25  

According to 12.9/4, "Inheriting constructors", when saying using X::X,

根据12.9/4“继承构造函数”,在使用X: X时,

A constructor so declared has the same access as the corresponding constructor in X.

这样声明的构造函数与X中的相应构造函数具有相同的访问权限。

So the inherited constructor is also protected.

因此,继承的构造函数也受到保护。

#1


25  

According to 12.9/4, "Inheriting constructors", when saying using X::X,

根据12.9/4“继承构造函数”,在使用X: X时,

A constructor so declared has the same access as the corresponding constructor in X.

这样声明的构造函数与X中的相应构造函数具有相同的访问权限。

So the inherited constructor is also protected.

因此,继承的构造函数也受到保护。