为驳回编译器自动提供复制构造函数和赋值构造函数的机能,可将相应的成员函数声明为private,但不予实现,或者使用像Uncopyable这样的base class也是一种做法
为防止对象被复制或者赋值,只需声明赋值构造函数或者赋值构造函数而不提供实现,且把他们的保护属性设为private
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
class E06
{
friend ostream& operator<<(ostream& out, E06& e06)
{
out << e06.m_name << " " << e06.m_age;
return out;
}
public:
E06() {}
E06(string name, int age) :m_name(name), m_age(age){}
~E06(){}
private:
E06(const E06&);
E06& operator=(const E06&);
string m_name;
int m_age;
};
int main()
{
E06 e06_f("小明", 20);
cout << e06_f << endl;
E06 e06_s(e06_f);//错误,不能使用复制构造函数
E06 e06_t;
e06_t = e06_f;//错误,不能使用赋值构造函数
system("pause");
return 0;
}
设置private的原因:防止友元或者成员函数内部进行赋值和复制
或者继承Uncopyable类,这个类的复制和赋值构造函数是private,且没有提供实现,这个类的派生类的赋值和复制构造函数会调用基类的相关构造函数,但是基类的复制和赋值是没有实现的,编译器就没有办法生成拷贝构造函数和赋值构造函数