c – 删除的复制构造函数导致删除的默认构造函数

前端之家收集整理的这篇文章主要介绍了c – 删除的复制构造函数导致删除的默认构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这段代码不能用 gcc 4.7.0编译:
class Base
{
public:
    Base(const Base&) = delete;
}; 

class Derived : Base
{
public:
    Derived(int i) : m_i(i) {}

    int m_i;
};

错误是:

c.cpp: In constructor ‘Derived::Derived(int)’:
c.cpp:10:24: error: no matching function for call to ‘Base::Base()’
c.cpp:10:24: note: candidate is:
c.cpp:4:2: note: Base::Base(const Base&) <deleted>
c.cpp:4:2: note:   candidate expects 1 argument,0 provided

换句话说,编译器不会为基类生成默认构造函数,而是尝试将已删除的复制构造函数作为唯一可用的重载调用.

这是正常的行为吗?

解决方法

C11§12.1/ 5指出:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X,a constructor having no parameters is implicitly declared as defaulted (8.4).

你的基地(const Base&)=删除;计为用户声明的构造函数,因此它禁止生成隐式默认构造函数.解决方法当然是声明它:

Base() = default;

猜你在找的C&C++相关文章