现在有这样一种要求,构造的对象都基于既定的模板,不允许任意构造。比如新建一个人姓氏的类,但是姓氏是固定的,不允许随便构造新的姓氏,于是可以定义枚举类。将除了<font color=red><b>Family_Name(const char * name)</b></font>以外的构造函数(拷贝,赋值)设为public。然后定义若干<font color=red><b>static Family_Name</b></font>供用户使用。
注: 枚举类不能为抽象类
class Family_Name{
private:
Family_Name(const char * name)
:name_(name){}
const char * name_;
public:
Family_Name(const Family_Name & other){
name_=other.name_;
}
Family_Name & operator=(const Family_Name & other){
name_=other.name_;
return *this;
}
public:
static Family_Name yang;
static Family_Name zhang;
static Family_Name liu;
static Family_Name zhao;
};
Family_Name Family_Name::yang("yang");
Family_Name Family_Name::zhang("zhang");
Family_Name Family_Name::liu("liu");
Family_Name Family_Name::zhao("zhao");
int main() {
Family_Name a = Family_Name::yang;
return 0;
}