#include <string>
using namespace std;
class Str
{
public:
explicit Str(string cc = "josan")
{
cout << "f1 iscalled\n";
str = cc;
}
explicit Str(Str& s)
{
cout << "f2 iscalled\n";
str = s.str;
}
void print();
~Str()
{
cout << "Bye\n";
}
/*const Str& operator=(const Str& ss);*/
private:
string str;
};
void Str::print()
{
cout << str << endl;
}
//const Str& Str::operator=(const Str& ss){
// cout <<"f3 is called\n";
// if (this ==&ss){
// return*this;
// }
// this->str =ss.str;
// return *this;
//}
int main()
{
{
//Str t;
//Str t();
//Str t{};
//Str t{ "szs" };
//Str t = { "szs" };
//Str t = Str{ "szs" };
//Str t("szs");
//Str t = "szs";
Str t = Str("szs");
//t.print();
//Str* st = new Str;
//Str* st = new Str{};
//Str* st = new Str();
//Str* st = new Str{ "szs" };
//Str* st = new Str("szs");
//st->print();
}
cin.get();
return 0;
}
以上是程序的测试代码主要考察构造函数以及复制构造函数的区别与联系。同时,加入explicit关键词的比较。通过测试代码,可以更好地理解上述概念。
测试环境为VS2013C++
下面的表格就是各个测试结果。
|
Str t; |
Str t(); |
Str t{}; |
Str t{"szs"} |
Str t={"szs"}; |
Str t=Str{"szs"} |
Str t("szs") |
Str t = "szs"; |
Str t = Str("szs"); |
Str(string cc = "josan") |
√ |
ⅹ |
√ |
√ |
√ |
√+Str(Str& s) |
√ |
√ |
√+Str(Str& s) |
explicit Str(string cc = "josan") |
√ |
ⅹ |
√ |
√ |
ⅹ |
√+Str(Str& s) |
√ |
ⅹ |
√+Str(Str& s) |
|
|
|
|
|
|
|
|
|
|
Str(Str& s) |
|
ⅹ |
|
|
|
√ |
|
|
√ |
explicit Str(Str& s) |
|
ⅹ |
|
|
|
ⅹ |
|
|
ⅹ |
备注:空格为无关 ⅹ表示无法通过 √表示存在调用关系 √+Str(Str& s) 表示构造以及拷贝构造同时存在调用
|
Str* st = new Str; |
Str* st = new Str{}; |
Str* st = new Str(); |
Str* st = new Str{ "szs" }; |
Str* st = new Str("szs"); |
Str(string cc = "josan") |
√ |
√ |
√ |
√ |
√ |
explicit Str(string cc = "josan") |
√ |
√ |
√ |
√ |
√ |
|
|
|
|
|
|
Str(Str& s) |
|
|
|
|
|
explicit Str(Str& s) |
|
|
|
|
|
备注:空格为无关 ⅹ表示无法通过 √表示存在调用关系 √+Str(Str& s) 表示构造以及拷贝构造同时存在调用