前言:
经过前面对类的认识,构造函数,拷贝构造,运算符重载,析构函数这些知识的学习,相信我们对c++已经有了一个初步的认识;那么本篇博客在前面的基础上,来对这些知识做一个综合性的整理,同时也是考察我们对其的掌握程度
(例1):
class Date
{
public:
Date()
{
cout << "Date()" << endl;
}
Date(const Date& d)
{
cout << "Date(const Date& d)" << endl;
}
Date& operator =(const Date& d)
{
cout << "Date& operator=(const Date& d)" << endl;
return *this;
}
~Date()
{
cout << "~Date()" << endl;
}
};
void f1(Date d)
{
}
int main()
{
Date d;
f1(d);
return 0;
}
问:这里构造函数、拷贝构造、析构函数分别调用了几次?
简单分析:创建对象d是调用1次构造函数,f1(d)这里由于f1()函数传参时是采用传值的方式,所以会先生成一个临时对象,这里调用了1次拷贝构造;最后两个对象都被析构,所以调用2次析构函数。
如果参数改为“引用”:
void f1(Date&d)
{
}
则:
(例2)如果我们把程序再稍加改动:
void f1(Date&d)
{
}
Date f2()
{
Date d;
return d;
}
int main()
{
Date d1;
f1(d1);
d1 = f2();
return 0;
}
那么试问:
构