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

  复制对象时要把对象的每一部分都赋值到位,尤其在有基类的时候容易遗漏复制
 

#include<iostream>
using namespace std;
class Date
{
public:
    Date(int d = 1, int m = 1, int w = 1) :day(d), month(m), weekday(w)
    {
        cout << "基类构造函数" << endl;
    }
    Date(const Date& rhs)
    {
        day = rhs.day;
        month = rhs.month;
    }
    Date& operator=(const Date& rhs)
    {
        day = rhs.day;
        month = rhs.month;
        return *this;
    }
    ~Date()
    {
        cout << "基类析构函数" << endl; 
    }
    void printDay()
    {
        cout << month << "月" << day << "日" << "周" << weekday << endl;
    }
private:
    int day;
    int month;
    int weekday;
};
int main()
{
    //忘记了赋值weekend
    Date day1;
    Date day2(2, 2, 2);
    day1 = day2;
    day1.printDay();
    /*
        基类构造函数
        基类构造函数
        2月2日周1
    */
    system("pause");
}

  在继承、派生体系中,对于派生类的复制控制函数,也要调用基类的复制控制,否则复制、赋值等操作只会作用于派生类特有的数据上:
  

#include<iostream>
using namespace std;
class Date
{
public:
    Date(int d = 1, int m = 1, int w = 1) :day(d), month(m), weekday(w)
    {
        cout << "基类构造函数" << endl;
    }
    Date(const Date& rhs)
    {
        init(rhs);
    }
    Date& operator=(const Date& rhs)
    {
        if (&rhs != this)
        {
            init(rhs);
        }
        return *this;
    }
    ~Date()
    {
        cout << "基类析构函数" << endl;
    }
    void printDay()
    {
        cout << month << "月" << day << "日" << "周" << weekday << endl;
    }
private:
    void init(const Date &rhs)
    {
        day = rhs.day;
        month = rhs.month;
        weekday = rhs.weekday;
    }
public:
    int day;
    int month;
    int weekday;
};
class DetailDay :public Date
{
public:
    DetailDay(const DetailDay& rhs) :year(rhs.year), Date(rhs)
    {
    }
    DetailDay(int y, int m, int d, int w) :year(y), Date(m, d, w)
    {}
    DetailDay& operator=(const DetailDay& rhs)
    {
        Date::operator=(rhs);
        year = rhs.year;
        return *this;
    }
    void printDay()
    {
        cout << year<<"年"<<month << "月" << day << "日" << "周" << weekday << endl;
    }
private:
    int year;
};
int main()
{
    DetailDay dt(2017, 5, 10, 3);
    dt.printDay();
    system("pause");

}

最后有一点需要注意:我们发现,复制构造函数和赋值构造函数里面很多内容是重复的。此时并不要用一个去调用另外一个,良好的编程习惯是定义一个init函数,让这两个函数都调用它,就想像程序中所做的那样。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值