=default的分析
目录
1. = default的分析
当声明一个类, 编译器会自动给他生成一个默认的构造函数, 和其他成员函数(拷贝赋值函数, 拷贝构造函数), 有些编译器还会自动生成移动构造函数, 移动赋值函数. 现在我们只关心构造函数
class Qoute
{
public:
private:
int num;
};
int main()
{
Qoute car; // 此时调用的编译器自动生成的构造函数
cout << "ok!" << endl;
}
编译器生成的默认构造函数形式为
Quote();
但是, 当你自定义一个或者多个构造函数之后, 编译器便不会再生成 Quote()这个默认构造函数了.
此时你再调用 Quote car;, 会提示错误.
class Quote
{
public:
Quote(int num){}
private:
int num;
};
int main()
{
Qoute car; // 此时调用的编译器自动生成的构造函数
cout << "ok!" << endl;
}
error: no matching constructor for initialization of 'Quote'
note: candidate constructor not viable: requires single argument 'num', but no arguments were provided
note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
没有匹配的构造器用来初始化Quote, 原因是编译器没有生成默认构造函数, 那怎么办?
- 自定义Quote(); 构造函数
- Quote() =default; 告诉编译器, 要求编译器自动生成Quote()构造函数
例如: 用方法2的方式
class Quote
{
public:
Quote() =default;
Quote(int num){}
private:
int num;
};
int main()
{
Qoute car; // 此时调用的编译器自动生成的构造函数
cout << "ok!" << endl;
}
那么使用"=default"符号有什么限制?
先看这个例子
class Quote
{
public:
Quote() =default;
// error: only special member functions may be defaulted
Quote(int num) = default;
// error: only special member functions may be defaulted
Quote(int num, int &date) = default;
// error: constructor cannot be redeclared
// note: previous definition is here
Quote(int = 0) = default;
private:
int num;
};
int main()
{
Qoute car; // 此时调用的编译器自动生成的构造函数
cout << "ok!" << endl;
}
错误: 只有指定的成员函数才可以被默认的. 那么哪些成员函数可以被默认呢?
class Quote
{
public:
Quote() =default; // 默认构造函数
Quote(int num) = default;
Quote(int num, int &date) = default;
Quote(Quote &) = default; // 默认拷贝构造函数
Quote& operator=(Quote&) =default; // 拷贝赋值函数
Quote(Quote &&) = default; // 默认移动构造函数
Quote& operator=(Quote&&) =default; // 移动赋值函数
~Quote() =default; // 默认析构函数
private:
int num;
};
所以可以由编译器默认生成成员函数有:
- 默认构造函数,
- 默认拷贝构造函数
- 拷贝赋值函数
- 默认移动构造函数
- 移动赋值函数
- 默认析构函数
在类内声明=default vs 在类外声明=default
在类内声明 = default, 则编译器认为默认构造函数是内联(inline)的;
在类外声明 = default, 则编译器认为默认构造函数不是内联的.

浙公网安备 33010602011771号