话不多说,直接看题,先看简单一点的。
第一题:
#include<iostream>
using namespace std;
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)//情况一
void F1(Date d)//情况二
{}
int main()
{
Date d;
F1(d);
system("pause");
return 0;
}
问以上代码调用构造函数,拷贝构造函数,赋值操作符重载,析构函数的次数
结果如下:
第二题:
#include<iostream>
using namespace std;
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;
}
};
//Date F2()
//{
// Date ret;
// return ret;
//}
Date F2()
{
Date ret;
return ret;
}
int main()
{
F2();
system("pause");
return 0;
}
结果如下:第三题:
#include<iostream>
using namespace std;
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;
}
};
Date F2()
{
Date ret;
return ret;
}
int main()
{ Date d1 = F2();//相当于Date d1(F2())
system("pause");
return 0;
}
结果:第四题:
#include<iostream>
using namespace std;
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()
{
F1(Date());
system("pause");
return 0;
}
结果:第五题:压轴题
这就是面试中爱考的构造函数,拷贝构造函数优化问题。