C++ explicit

说明

  • 写类的构造函数时,如果不加explicit进行修饰时,可能会发生一些隐式转换
  • 对于一个类,如果没有找到需要进行隐式转换的理由,则建议加上explicit进行修饰,避免不可预料的转换问题

代码

#include<iostream>
#include<exception>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<iterator>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<concurrent_priority_queue.h>
#include<algorithm>
#include<numeric>
#include<functional>  //bind
#include<map>
#include<set>
#include<unordered_map>
#include<memory>
#include<assert.h>
#include<tuple>
#include<regex>

using namespace std;

class ExplicitClass
{
public:

    ExplicitClass(string s) : height(0), width(0)
    {
        name = s;
        cout << name << " has been initalized!" << endl;
    }

    int compare(const ExplicitClass &ec)
    {
        return strcmp(name.c_str(), ec.name.c_str());
    }

private:
    double height;
    double width;
    string name;
};

int main()
{
    cout << "start!" << endl;

    ExplicitClass c1("aa");
    string n("bb");
    cout << c1.compare(n) << endl;

    cout << "end!" << endl;
    system("pause");
    return EXIT_SUCCESS;
}

* 说明:上面的代码中,没有加上explicit,则在传入字符串进行compare时,发现也构造一个ExplicitClass的临时对象(运行时可以发现有两次构造输出)
* 如果将构造函数改为

    explicit ExplicitClass(string s) : height(0), width(0)
    {
        name = s;
        cout << name << " has been initalized!" << endl;
    }

则会发生编译错误,因为不允许隐式转换

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值