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

如果你声明自己的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成分的责任,
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值