What is the purpose of ‘explicit’ in C++?

In C++, the explicit keyword is used to decorate single-argument constructors, its purpose is to prohibit implicit conversion. When a constructor is declared as explicit, it can only be explicitly called and cannot be implicitly converted to other types.

Using explicit to modify constructors can prevent potential errors and unexpected behaviors, ensuring the explicitness and safety of type conversions. By prohibiting implicit conversions, ambiguity and misunderstanding in the code can be reduced, improving its readability and maintainability.

Here is an example using the explicit keyword:

class MyClass {
public:
    explicit MyClass(int value) {
        // 构造函数的实现
    }
};

void func(MyClass obj) {
    // 函数的实现
}

int main() {
    MyClass obj1(10); // 直接调用构造函数
    MyClass obj2 = 20; // 错误,禁止隐式转换
    func(obj1); // 正确,显式调用构造函数
    func(30); // 错误,禁止隐式转换
    return 0;
}

In the example above, the constructor of MyClass is modified with the explicit keyword, prohibiting implicit conversions. In the main function, the construction of obj1 is correct because the constructor is explicitly called, while the constructions of obj2 and func(30) are incorrect as they attempt to perform implicit conversions, which are disallowed by the explicit keyword.

Leave a Reply 0

Your email address will not be published. Required fields are marked *