Effective C++ 条款12:复制对象时勿忘其每一个成分 学习笔记

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

<textarea readonly="readonly" nam ="code" class="c++">
void logCall(const string& funcName);
class Customer{
public:
    Customer(string b):name(b){}
    Customer(const Customer& rhs);
    Customer& operator = (const Customer& rhs);
    string name;//将成员变量声明为public便于实验观察
};

void logCall(const string &funcName){
    cout << "funcName = " << funcName << endl;
}

Customer::Customer(const Customer &rhs):name(rhs.name){
    logCall("Customer copy constructor.");
}

Customer& Customer::operator = (const Customer& rhs){
    logCall("Customer copy assignment operator.");
    name = rhs.name;
    return *this;
}

class PriorityCustomer:public Customer{
public:
    PriorityCustomer(int a, string b):Customer(b),priority(a){}
    PriorityCustomer(const PriorityCustomer& rhs);
    PriorityCustomer& operator = (const PriorityCustomer& rhs);
    int priority;//将成员变量声明为public便于实验观察
};
// 拷贝构造函数中 Customer(rhs) 编译器强制要求加上,在拷贝赋值函数中没有向基类传递信息,作为对比
PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs)
    :Customer(rhs), priority(rhs.priority){
    logCall("PriorityCustomer copy constructor.");
}

PriorityCustomer& PriorityCustomer::operator =(const PriorityCustomer& rhs){
    logCall("PriorityCustomer assignment operator.");
    priority = rhs.priority;
    return *this;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    PriorityCustomer pc1(10,"Hello");
    PriorityCustomer pc2(100,"World");
    PriorityCustomer pc3(pc2);
    pc1 = pc2;
    cout<<"pc3.priority = "<<pc3.priority<<endl;
    cout<<"pc3.name = "<<pc3.name<<endl;
    cout<<"pc1.priority = "<<pc1.priority<<endl; 
    cout<<"pc1.name = "<<pc1.name<<endl;
    return a.exec();
}
</textarea>

此时得到的结果是


可见拷贝构造函数复制了每一个成员,而拷贝赋值函数并没有全部复制。对拷贝赋值函数进行修改,加入基类的拷贝赋值函数:

<textarea readonly="readonly" nam ="code" class="c++">
PriorityCustomer& PriorityCustomer::operator =(const PriorityCustomer& rhs){
    logCall("PriorityCustomer assignment operator.");
    Customer::operator =(rhs);
    priority = rhs.priority;
    return *this;
}
</textarea>
最终得到的结果是


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值