[C++] explicit关键字使用方法

C++中,构造函数可以用作自动类型转换,但是这种转换不一定是程序所需要的,有时会导致错误的类型转换。

下面的代码,在mian函数中,将一个整形赋值为对象类型。

#include "iostream"

using namespace std;

class Student {
private:
    int a;
public:
    Student(int tmp) {
        this->a = tmp;
    }

    void print() {
        cout << a << endl;
    }
};

int main(void) {
    // 标准赋值
    Student stu1(123);
    // 隐式赋值
    Student stu2 = 123;
    stu1.print();
    stu2.print();

    return 0;
}

上面的代码可以正常编译运行,输出123,456

因为普通构造函数能够被隐式的调用,编译器就自动调用这个构造器。

虽然隐式转换有方便之处,但是除非特意设计,否则隐式转换常常带来程序的逻辑错误,而且这种错误发生了很难查找。

explicit 关键字,就是为了防止类型错误转换,禁止构造函数在隐式转换中使用。

建议所有构造函数都添加 explicit 关键字,当真正需要转换时再删除 explicit

下面的代码,添加了 explicit 关键字,就会编译报错

#include "iostream"

using namespace std;

class Student {
private:
        int a;
public:
    // 禁止隐式转换
    explicit Student(int tmp) {
        this->a = tmp;
    }

    void print() {
        cout << a << endl;
    }
};

int main(void) {

    Student stu = 456;
    stu.print();

    return 0;
}
原文地址:https://www.cnblogs.com/lialong1st/p/12013701.html