条款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函数共同调用。