What is the purpose and usage of the c++ explicit keyword?

In C++, the keyword “explicit” is used to decorate single-parameter constructor functions of a class, serving the purpose of preventing implicit conversion. It is used as follows:

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

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

In the code above, the explicit keyword is used to modify the constructor of MyClass, preventing it from being implicitly called. Therefore, assigning an integer value directly to an object of type MyClass (such as MyClass obj2 = 10;) will result in a compilation error. However, objects can still be created using explicit calls (such as MyClass obj3 = MyClass(15);).

Using the explicit keyword can prevent unintended implicit conversions, improving the readability and safety of the program. In particular, using the explicit keyword in constructors with a single parameter can prevent the compiler from performing implicit conversions.

Leave a Reply 0

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