条款12:赋值对象时勿忘记其每一个成分

来源:互联网 发布:23端口是什么服务 编辑:程序博客网 时间:2024/05/29 04:39

如果你声明自己的copying函数,当你你的代码出错时编译器不会告诉你

void logCall(const string& funcName){    cout << funcName << endl;}class Customer{public:    Customer(const string& str) :name(str)    {    }    Customer(const Customer& rhs):name(rhs.name)    {        logCall("Customer copy Customer");    }    Customer& operator=(const Customer& rhs)    {        logCall("Customer copy assignment operator");        name = this->name;        return *this;    }private:    string name;};Customer c("Hello");Customer a(c);//上述代码看起来很好,直到另一个成员变量加入改变了格局class Date{}class Customer{public:private:    string name;    Date lastTransaction;};/*上面的代码增加了成员变量lastTransaction,copying函数执行的是局部拷贝,复制了顾客的name但是没有复制新添加的lastTransaction。*/class PriorityCustomer :public Customer{public:    PriorityCustomer()    {    }    PriorityCustomer(const PriorityCustomer& rhs):priority(rhs.priority)    {        logCall("PriorityCustomer copy constructor");    }    PriorityCustomer& operator=(const PriorityCustomer& rhs)    {        logCall("PriorityCustomer copy assignment constructor");        priority = rhs.priority;        return *this;    }private:    int priority=1;};PriorityCustomer a;PriorityCustomer b(a);/*上面的代码发生了继承,PriorityCustomer的copying函数自己申明的成员变量,但是每个PriorityCustomer还包含所继承Customer的成员变量,这些成员变量未复制。*/PriorityCustomer(const PriorityCustomer& rhs):priority(rhs.priority),Customer(rhs){        logCall("PriorityCustomer copy constructor");}PriorityCustomer& operator=(const PriorityCustomer& rhs){        logCall("PriorityCustomer copy assignment constructor");        Customer::operator=(rhs);        priority = rhs.priority;        return *this;}/*当你为derived class撰写copying函数时,你也要承担复制base class成分的责任,*/
原创粉丝点击