Effective C++条款12

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

#include<iostream>

class Date{
public:
    Date()=default;
    Date(const int&month,const int&day)
        :m_month(month),m_day(day)
        {}
    void Init_Date()
    {
        std::cout<<"Please input month and day:";
        std::cin>>this->m_month>>this->m_day;
    }
    std::pair<int,int> GetDate()const{
        auto m_Date=std::make_pair(this->m_month,this->m_day);
        return m_Date;
    }
private:
    int m_month;
    int m_day;
};

class Widget{
public:
    //Widget()=default;
    Widget(const std::string&name)
        :m_name(name)
        {m_date.Init_Date();}
    Widget(const Widget&rhs)
        :m_name(rhs.m_name)
        {}
    Widget&operator=(const Widget&rhs)
    {
        this->m_name=rhs.m_name;
        return *this;
    }
    virtual ~Widget()=0;
protected:
    std::string m_name;
    Date m_date;
};

Widget::~Widget(){}

class DerivedWidget:public Widget{
public:
    DerivedWidget(const std::string&name,const int& data)
        :Widget(name),
         derived_data(data)
         {}
    DerivedWidget(const DerivedWidget&rhs)
        :Widget(rhs),
        derived_data(rhs.derived_data)
        {}
    DerivedWidget&operator=(const DerivedWidget&rhs)
    {
        Widget::operator=(rhs);
        derived_data=rhs.derived_data;
        return *this;
    }
    friend std::ostream& operator<<(std::ostream&os,const DerivedWidget&rhs);
private:
    int derived_data;
};

std::ostream& operator<<(std::ostream&os,const DerivedWidget&rhs){
    os<<"Name:"<<rhs.m_name<<" "
      <<"Date:"<<rhs.m_date.GetDate().first<<"."<<rhs.m_date.GetDate().second
      <<" "<<"Derived_Data:"<<rhs.derived_data;
    return os;
}

请记住:

  • Copying函数应该确保复制“对象内的所有成员变量”及“所有base class成分”。
  • 不要尝试以某个copying函数实现另一个copying函数。应该将共同机能放进第三个函数中,并由两个copying函数共同调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值