拷贝构造是一种特殊的构造函数,它显式的第一个参数是本类类型的引用,如果还有其他参数的话,其他参数必须有默认值(一般情况没有其他参数,只有类类型引用)
例:
class Date
{
public:
//默认构造函数
Date(int year = 0, int month = 0, int day = 0)
:_year(year)
,_month(month)
,_day(day)
{}
//拷贝构造,参数只有本类型引用
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
//赋值运算符重载,稍后会讲
Date& operator=(const Date& d);
void Print()
{
cout << _year << "年" << _month << "月" << _day << "日" << endl;
}
private:
int _year;
int _month;
int _day;
};
Date& Date::operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
赋值重载是一个运算符重载函数,是一个默认的成员函数,用于两个已经存在的对象的拷贝赋值,这里需要与拷贝构造相区分,拷贝构造是用一个对象去拷贝另外一个正在创建的对象
例:
//这里采用的Date类即为上例中Date类
int main()
{
Date d1(2024,7,15);
Date d2;
d2 = d1;//这里d1与d2两个对象都已经创建好,已经存在了,是将d1的值拷贝给d2
//注意下面d3与d4都是拷贝构造,特别注意对于d4,它不是赋值重载而是直接使用d2的值来拷贝构造d4
Date d3(d1);
Date d4 = d2;
d1.Print();
d2.Print();
d3.Print();
d4.Print();
return 0;
}
输出结果如下:
