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

本文通过实例详细解析了C++中构造函数与复制构造函数的区别及联系,特别关注了explicit关键字的作用,帮助读者深入理解这些概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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");

       

 

 

        //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) 表示构造以及拷贝构造同时存在调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值