不需要编译器自己生成的函数,就应该明确拒绝
在C++类的设计中要注意防止类自身生成的函数对实际应用的干扰。举个例子:一个表示个人信息的类,class PersonalInformation{ ..... };,对于个人信息,从原则上来说不可能一样的,但是实际操作时候我们可能会出现PersonalInformation p1 = p2;这样的assigned操作。这对于这个类毫无用处,而且会产生一些不必要的BUG。下面就介绍两种方法来拒绝编译器自己生成的函数(代码均通过VS2008编译运行)。
方法一、定义要屏蔽的函数为私有函数,但是同时不实现它,在链接期拒绝
#include <iostream>
#include <string>
class PersonalInfor
{
public:
int show_ID(void )
{
std::cout<<personal_ID<<std::endl;
return NULL;
}
PersonalInfor(const std::string& id):personal_ID(id)
{}
private:
PersonalInfor(const PersonalInfor&);//定义要屏蔽的函数为私有函数,但是同时不实现它
PersonalInfor& operator=(const PersonalInfor&);
std::string personal_ID;
};
int main()
{
PersonalInfor wang("2432222");
wang.show_ID();
PersonalInfor li = wang;//会提示cannot access private member declared in class 'PersonalInfor'
system("pause");
}
方法二、继承一个专门阻止某动作的Base_class,在编译器拒绝该行为
#include <iostream>
#include <string>
class UnCopyable//定义一个阻止这个行为的基类
{
protected://构造函数protected模式
UnCopyable(){}
~UnCopyable(){}
private:
UnCopyable(const UnCopyable& );
UnCopyable& operator=(const UnCopyable&);
};
class PersonalInfor:private UnCopyable//启用私有继承
{
public:
int show_ID(void )
{
std::cout<<personal_ID<<std::endl;
return NULL;
}
int set_id(const std::string& id)
{
personal_ID=id;
return NULL;
}
private:
std::string personal_ID;
};
int main(void)
{
PersonalInfor wang;
wang.set_id("1121212");
wang.show_ID();
PersonalInfor li = wang;
//PersonalInfor li(wang);//编译期提示错误
system("pause");
}