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

文章讲述了在C++编程中,添加新成员变量时需更新构造函数和拷贝构造,以及在派生类复制时必须包含基类成分的修正示例。
摘要由CSDN通过智能技术生成

1.不要忘记复制成员变量

class customer
{

public:
    customer(const customer & c)
        :name(c.name)
    {}
    customer& operator=(const customer& c)
    {
        name = c.name;
        return *this;
    }
private:
    std::string name;

};

在成员变量中,新增一个Transaction变量,切记要修改,构造函数和拷贝构造,如果不新增编译器不会报错,很难令人察觉。

class customer
{

public:
    customer(const customer & c)
        :name(c.name)
        ,Transaction(c.Transaction)
    {}
    customer& operator=(const customer& c)
    {
        name = c.name;
        Transaction = c.Transaction;
        return *this;
    }
private:
    std::string name;
    std::string Transaction;
};

2.派生类复制不要忘记基类的成分

错误代码,在复制的时候完全忘记基类成分。

class PriorityCustomer : public customer
{
public:
    PriorityCustomer(const PriorityCustomer &p)
        :priority(p.priority)
    {}

    PriorityCustomer& operator=(const PriorityCustomer& p)
    {
        priority = p.priority;
    }
private:
    int priority;
};

正确代码

class PriorityCustomer : public customer
{
public:
    PriorityCustomer(const PriorityCustomer &p)
        :customer(p)
        ,priority(p.priority)
        
    {}

    PriorityCustomer& operator=(const PriorityCustomer& p)
    {
        customer::operator=(p);
        priority = p.priority;
        return *this;
    }
private:
    int priority;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值