假设有一个类,需要实例中的c属性保持唯一
那么:就需要构造函数生成唯一的c值;同时用另外一个实例新建一个实例,也就要保持唯一,那么就需要拷贝函数分配唯一值;同时我们也可能将一个类的实例赋值给另外一个实例,但是默认复制运算构造函数不能保证唯一
#include <iostream>
#include <thread>
#include <map>
using namespace std;
class CopyStruct {
public:
CopyStruct();
CopyStruct(const CopyStruct &);
CopyStruct& operator=(const CopyStruct &c);
static int b;
int c=0;
};
CopyStruct::CopyStruct(){
this->b=this->b+1;
c=this->b;
}
CopyStruct::CopyStruct(const CopyStruct &c){
b=b+1;
this->c=b;
}
//如果这里注释掉,就会出现c,b实例的c值是同样的
CopyStruct& CopyStruct::operator=(const CopyStruct &c){
return *this;
}
int CopyStruct::b =10;
int main()
{
CopyStruct a;
CopyStruct b;
CopyStruct c=b;
std::cout<<a.c<<b.c<<c.c<<std::endl;
c=b;
std::cout<<"默认复制构造函数之后:"<<c.c<<std::endl;
/*
map<string,string> arrays;
arrays["name"]="cccc";
std::cout<<arrays["name"]<<std::endl;
using name=const char *;
name a="this is a aliaes";
std::cout<<a<<std::endl;
*/
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30221425/viewspace-2666310/ ,如需转载,请注明出处,否则将追究法律责任。