我们编写了一个类,但不允许这个类进行复制(只允许生成)该怎么办呢?
只需要创建一个类,把复制构造函数(左值引用和右值引用)还有等号重载(左值引用和右值引用)设置成delete,然后使目标类继承该类就可以了。
//不可复制的类:
#include <cstdlib>
#include <string>
using namespace std;
class NotCopyable{
NotCopyable() = default;
NotCopyable(const NotCopyable& ) = delete;
NotCopyable(NotCopyable&& ) = delete;
NotCopyable& operator= (const NotCopyable& ) = delete;
NotCopyable& operator= (NotCopyable&&) = delete;
};
struct Student:private NotCopyable
{
string name;
time_t birtyday;
};
int main()
{
Student a;
Student b = a; //报错
a = b; //报错
return 0;
}
这样student类就只允许创建,不允许复制了