【问题标题】:Private and default constructor in C++11 and gccC++11 和 gcc 中的私有和默认构造函数
【发布时间】:2013-02-08 09:21:36
【问题描述】:

代码:

struct A
{
    private:
    A() = default; // Version 1.
};
struct B : public A
{};

struct C
{
    private:
    C() {}; // Version 2.
};
struct D : public C
{};

int main()
{
   B b;  // Compiles          under g++ 4.7.2
   D d;  // Compilation error under g++ 4.7.2
}

还有两种情况(使用 gcc 4.7.2):

  • 如果我编译这段代码(使用版本 1 的 A 的构造函数),没有问题。
  • 如果我使用第二个构造函数,gcc 会告诉我 D::D() 是私有的。

问题:如果我使用默认构造函数,为什么问题会消失?如果A 具有私有构造函数,则其他类永远不能创建A 的实例,甚至不能创建其派生类,无论其构造函数实现的“默认性”如何。

【问题讨论】:

    标签: c++ inheritance c++11 private default-constructor


    【解决方案1】:

    这对我来说就像一个 GCC 错误

    关于成员访问控制的整个第 11 条和关于默认构造函数的第 8.4.2 节都没有提到任何关于覆盖默认构造函数的可访问性级别。

    此外,此代码在 Clang 3.2 和 Intel ICC 13.0 上编译。

    另一方面,如果您对第 X 行进行注释,则以下行将不会按照您的想法行事:

    B b(); // This will declare a function that accepts no argument
           // and returns a value of type B
    

    如果你去掉括号,你应该看到问题弹出:

    B b; // ERROR: Constructor of A is private
    

    但是,GCC 4.7.2(错误地)不会引发编译错误。这似乎还没有在 GCC 4.8.0 的 beta 版本中得到修复(截至 build 20130127)。

    【讨论】:

    • line X 都没有评论?
    • @JonathanWakely:谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 2019-05-07
    • 2016-06-27
    • 2020-05-14
    • 2018-11-25
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多