拷贝构造函数
1.拷贝(复制)构造函数语法
类名::类名(const 类名 & [形式参数])
Date::Date(const Date & date); //声明
Date::Date(const Date & date) //实现
{
year = date.year;
month = date.month;
day = date.day;
}
//上下文补充部分
class Date
{
public:
Date(int year, int month, int day):year(year), month(month), day(day) { }
Date(const Date &date);
Date(Date date);
Date &operator =(const Date &date); //重载赋值运算符
private:
int year;
int month;
int day;
}
2.拷贝(复制)构造函数调用时机
(1)用类的已知对象定义该类的一个正在被创建的对象 Date u; Date t = u; //调用复制构造
(2)对象作为实参传递给函数形参
Date u;
Date t(u); //调用复制构造
(3)对象作为函数返回值
Date u;
Date fun()
{
Date t;
return t; //调用复制构造
}
3.补充
对于2.(1)中“Date t = u;”会让人误以为应该是调用了“=”运算符,其实“=”运算符调用时机为:
Date today, tomorrow;
Date yestoday = today; //调用复制构造函数
tomorrow = today; //调用 operator = 运算符