【问题标题】:Inherit from a class that has the copy constructor deleted从删除了复制构造函数的类继承
【发布时间】:2014-05-30 02:43:33
【问题描述】:

我有 base 类,它只包含私有默认构造函数和公共删除的复制构造函数,没有别的。

class base {
private:
    base() = default;

public:
    base(const base&) = delete;
};

如果我尝试从base 继承并创建类derived 的实例,如下所示,g++ 4.8.2 不会编译我的代码,但 VC++ 2013 会。

class derived : public base {
private:
    derived() = default;
};

derived x;

那么,它是 g++ 或 VC++ 2013 中的一个错误,只是忽略了一些东西吗?

这是完整的代码...

class base {
private:
    base() = default;

public:
    base(const base&) = delete;
};

class derived : public base {
private:
    derived() = default;
};

derived x;

int main() { 
}

...和 ​​g++ 错误信息。

main.cpp:12:5: error: 'constexpr derived::derived()' is private
     derived() = default;
     ^
main.cpp:15:9: error: within this context
 derived x;
         ^
main.cpp: In constructor 'constexpr derived::derived()':
main.cpp:3:5: error: 'constexpr base::base()' is private
     base() = default;
     ^
main.cpp:12:5: error: within this context
     derived() = default;
     ^
main.cpp: At global scope:
main.cpp:15:9: note: synthesized method 'constexpr derived::derived()' first required here
 derived x;
         ^

【问题讨论】:

  • 我认为这是 VS2013 中的一个错误。构造函数是私有的,因此您不能创建该类的实例。
  • 但是如果派生类没有从类基类继承,g++ 会让它编译。可能标记为默认的默认构造函数就像隐式声明的默认构造函数一样。
  • @so61pi g++ 不会诊断这种情况的事实是GCC bug 56429
  • @Casey 哦,谢天谢地,我关于显式私有构造函数和隐式声明的默认构造函数的想法是错误的:D。
  • 但是现在,和 g++ 一样,VC++ 2013 也忽略了 Explicitly default private constructor。

标签: c++ c++11 visual-studio-2013 compiler-bug g++4.8


【解决方案1】:

您误读了错误,它告诉您derived 的默认构造函数不可访问(是private),因此您不能使用它来创建该类型的对象。现在在derived 级别设置public 将无济于事,因为base 构造函数也是private,因此不能在derived 的构造函数中使用。

为什么你希望那些构造函数是private

【讨论】:

  • 我刚刚使用 VC++ 2013 & g++ 测试了一些 C++11 特性:D。
猜你喜欢
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 2012-05-26
  • 2015-05-25
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 2015-04-11
相关资源
最近更新 更多