复制对象时要把对象的每一部分都赋值到位,尤其在有基类的时候容易遗漏复制
#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函数,让这两个函数都调用它,就想像程序中所做的那样。