您的位置:首页 > 其它

构造函数,拷贝构造的优化相关问题

2018-02-01 18:58 197 查看
话不多说,直接看题,先看简单一点的。

第一题:

#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;
}结果:

第五题:压轴题







这就是面试中爱考的构造函数,拷贝构造函数优化问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐