小总结:赋值操作符和复制初始化通常在一起使用,两个都有合成版本,有时候可以不用管
另外private: Class(const Class &);可以防止用户代码复制该类对象,
但是友元和成员仍可进行复制,就干脆只声明不定义,此种方法只是防止出现结果,但不能阻止调用,调用将导致链接失败。
//那么,怎么用成员和友元来测试这个复制呢,明天解决
回忆了一下static知识点,利用变化的静态变量,标识唯一ID,因为统计用,初始count是0,初始ID是1,所以用的前置自加运算符
小问题是赋值运算符:遗忘知识点了?
Employee em2 = em1;//单纯等价于后者
Employee em2( em1);//两个完全没区别,这里边无视operator=了?
#include"head.h"
//ID是唯一的,要想办法标识
class Employee{
public:
//构造函数
Employee(): name(""), ID(++number){std::cout << "defalut-constructor: " << std::endl;}
Employee(std::string s): name(s), ID(++number){std::cout << "one-parm-constructor: " << std::endl;}
//复制构造函数
Employee(const Employee &);
//赋值操作符
Employee& operator = (const Employee &);
//统计与测试用接口
static int getCount(){ return number;}
int getID(){ return ID;}
std::string getName(){ return name;}
private:
std::string name;
int ID;
static int number;//标记ID和统计数量用
};
//相关成员的定义
int Employee::number = 0;
Employee::Employee(const Employee & em) : name(em.name), ID(++number){std::cout << "copy-constructor: " << std::endl;}
Employee&
Employee::operator = (const Employee &em){
std::cout << "assignment: " << std::endl;
// ID = em.ID;//区别于合成赋值操作符,可以保护ID
name = em.name;
return *this;
}
int main(){
Employee em1("hu");//初始化
Employee em2 = em1;//不自定义赋值操作符情况下,默认的赋值操作怎么不更改ID,自定义成复制ID也不成,这个语句就算一个copy-construction,没有assign
std::cout << "====================" << std::endl;
Employee em3(em1);//复制初始化
Employee em4;
em4 = em1;//不自定义赋值操作符在这会出错,他俩ID一样了。
std::cout << "ID: " << em1.getID() << " : " << em1.getName() << std::endl;
std::cout << "ID: " << em2.getID() << " : " << em2.getName() << std::endl;
std::cout << "ID: " << em3.getID() << " : " << em3.getName() << std::endl;
std::cout << "ID: " << em4.getID() << " : " << em4.getName() << std::endl;
std::cout << "统计: " << em1.getCount() << std::endl;
std::cout << "统计: " << Employee::getCount() << std::endl;
}