/*输出如下:
Constructor called. // 1TDate day1(1998,5,26);
Constructor called. // 2TDate day3;
Copy Constructor called. //3TDate day2(day1);
Copy Constructor called. //4TDate day4 = day2;
Copy Constructor called. //5为函数f的参数Q构造
Copy Constructor called. //6构造R
Copy Constructor called. //7函数f按值返回构造无名对象
Destructor called. //8 析构R
Destructor called. //9 析构f按值返回构造的无名对象
Destructor called. //10析构参数Q
1998-5-26 //11day3.Print();
Destructor called. //12析构day4
Destructor called. //13析构day2
Destructor called. //14析构day3
Destructor called. //15析构day1*/
你可能会奇怪day3 = day2;为什么没有构造,其实在第二句Constructor called. // 2TDate day3;day3已经构造了,day3=day2;语句不会在次构造它只会掉用默认的重载operator=函数进行值的转换,你要清楚构造函数和复制构造函数都要构造一个对象,operator=只是赋值不构造对象,不管是用复制构造函数还是构造函数构造的对象都要用同一个析构函数去析构。为了验证到底是先析构R还是先析构函数f按值返回构造的无名对象,可以改为下面的代码:
#include<iostream>
using namespace std;
class TDate
{
int year,month,day;
public:
TDate(int y=2007,int m=1,int d=1);
TDate(const TDate &date);
operator =(const TDate &date);
~TDate();
void Print();
};
TDate::TDate(int y,int m,int d)
{
year = y;
month = m;
day = d;
cout<<"Constructor called.\n";
}
TDate::TDate(const TDate &date)
{
year = date.year;
month = date.month;
day = date.day;
cout<<"Copy Constructor called.\n";
}
void TDate::Print()
{
cout<<year<<"_"<<month<<"_"<<day<<endl;
}
TDate::~TDate()
{
if(year==1997) cout<<"R Destructor called.\n";
else cout<<"Destructor called.\n";
}
TDate::operator=(const TDate &date)
{
year = date.year;
month = date.month;
day = date.day;
cout<<"operator=函数在执行.\n";
}
TDate f(TDate Q)
{
TDate R(1997,5,26);
return Q;
}
void main()
{
TDate day1(1998,5,26);
TDate day3;
TDate day2(day1);
TDate day4 = day2;
day3 = day2;
day3 = f(day2);
day3.Print();
}
可以得到证明:
/*Constructor called. // 1TDate day1(1998,5,26);
Constructor called. // 2TDate day3;
Copy Constructor called. //3TDate day2(day1);
Copy Constructor called. //4TDate day4 = day2;
operator=函数在执行 //day3 = day2;
Copy Constructor called. //5为函数f的参数Q构造
Copy Constructor called. //6构造R
Copy Constructor called. //7函数f按值返回构造无名对象
R Destructor called. //8 析构R
Destructor called. //9 析构f按值返回构造的无名对象
operator=函数在执行 //day3 = f(day2);
Destructor called. //10析构参数Q
1998-5-26 //11day3.Print();
Destructor called. //12析构day4
Destructor called. //13析构day2
Destructor called. //14析构day3
Destructor called. //15析构day1*/
这时你应该完全了解了吧,同时还对operator=函数有了一定的认识