[c++] explicit 关键字的作用

用explicit声明的构造函数可以很好地避免隐式类型转换问题

请看下面的例子:

#include "stdafx.h"
#include "iostream"
using namespace std;
class A
{
public:
    A(int x = 5);
    ~A();
    void Print();

private:
    int num;
};

A::A(int x)
{
    num = x;
}

A::~A()
{
}

void A::Print()
{
    std::cout << num << std::endl;
}

int main()
{
    A a;
    a = 10;
    a.Print();
    return 0;
}


代码执行后,输出的结果为10,我们会发现,我们没有重载'='运算符,但是去可以把内置的int类型赋值给了对象A. a = 10; 实际上,10被隐式转换成了下面的形式,所以才能这样。s = A temp(10);

当程序变成了以下样子后:

#include "stdafx.h"
#include "iostream"
using namespace std;
class A
{
public:
    explicit A(int x = 5);
    ~A();
    void Print();

private:
    int num;
};

A::A(int x)
{
    num = x;
}

A::~A()
{
}

void A::Print()
{
    std::cout << num << std::endl;
}

int main()
{
    A a;
    a = 10; // 会报错,无法编译
    a.Print();
    return 0;
}


程序中会报错,通过两个例子我们知道:explicit可以抑制内置类型隐式转换,所以在类的构造函数中,最好尽可能多用explicit关键字,防止不必要的隐式转换。

参考链接:https://blog.csdn.net/qq_37233607/article/details/79051075

你可能感兴趣的:(其他不归路)