在受保护时使用基类构造函数

Using base class constructor when it is protected

提问人:shane 提问时间:9/20/2017 最后编辑:shane 更新时间:9/20/2017 访问量:280

问:

我想在子类中使用基类构造函数,基类构造函数受到保护,因此如果没有子类就无法实例化它。

class A {
protected:
    A() {}
};

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

但是我不能在没有编译器抱怨受保护的情况下使用这样的 using 指令,即使 using 在公共块中也是如此。B::B()

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

此行为在何处指定?

编辑

我试图简化这个例子,但没有检查它是否编译,显然它有一个微不足道的构造函数,但这段代码不能编译

class A {
protected:
    A(int x) {}
};

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

int main() {
  B b(4);
}

有错误

main.cpp: In function 'int main()':
main.cpp:12:8: error: 'A::A(int)' is protected within this context
   B b(4);
        ^
main.cpp:3:5: note: declared protected here
     A(int x) {}
     ^

exit status 1
C++ C++11 using 指令

评论

0赞 user0042 9/20/2017
“所以没有子类就无法实例化它”
4赞 François Andrieux 9/20/2017
我想你忘了在你的例子中继承。我派生自,这些示例似乎工作正常。BABA
3赞 Richard Critten 9/20/2017
该代码不支持您的问题,请创建一个最小的可重现示例
2赞 Yakk - Adam Nevraumont 9/20/2017
显然,你的意思是从A那里继承,但你的意思是公开、私下还是受保护?你的错误到底是什么
1赞 Praetorian 9/20/2017
答案是“因为标准是这么说的”——见 stackoverflow.com/a/24015931/241631

答: 暂无答案