目录
1.默认生成的函数
2.无法生成的情况
2.1当成员函数有引用 或者 被const修饰
2.2.operator=在基类被私有
1.默认生成的函数
class empty {};
//相当于
class empty
{
public:
empty(){ ... } // 构造函数
empty(const empty& rhs) { ... }// 拷贝构造
~empty(){ ... } //析构函数
empty &operator=(const empty& rhs) { ... } //拷贝赋值
};
这些默认生成的函数都是public和inline。
如果程序员不去写这些函数 ,他们会在被调用的时候由编译器生成。
2.无法生成的情况
2.1当成员函数有引用 或者 被const修饰
template
class NameObject
{
public:
NameObject(std::string &name, const T& obj)
{
}
private:
std::string &nameValue;
const T ObjcetValue;
}
std::string pet1 ("dog", 2);
std::string pet2 ("cat", 2);
pet1 = pet2;
当成员函数有引用 或者 被const修饰,编译器是不会自动生成 operator= 的,因为 &必须在定义的时候初始化,而且初始化之后不可以进行修改,const也同样,这个时候需要程序员手动写operator=。
2.2.operator=在基类被私有
operator=被声明为私有,派生类生成的默认operator=回去先调用基类类的operator=,但是没有权限,编译器也无能为力。