您的位置:首页 > 其它

构造函数以及拷贝构造函数区别以及explicit的对比

2016-11-03 20:22 375 查看
#include <iostream>
#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");
       
 
 
     
4000
  
//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)
表示构造以及拷贝构造同时存在调用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐