How to use ‘explicit’ in C++?

In C++, the keyword ‘explicit’ is used to modify single parameter constructor functions to prevent implicit conversion. When a single parameter constructor function is marked with the ‘explicit’ keyword, it can only be called explicitly and cannot be used in implicit conversions.

Here is an example of using the explicit keyword:

class MyInt {
public:
    explicit MyInt(int num) : value(num) {}

    int getValue() const {
        return value;
    }

private:
    int value;
};

void printInt(const MyInt& num) {
    std::cout << num.getValue() << std::endl;
}

int main() {
    MyInt myNum(5); // 直接调用构造函数
    printInt(myNum); // 隐式转换为MyInt对象,通过显式调用的方式传递给printInt函数
    // printInt(5); // 错误,不能隐式转换为MyInt对象
    printInt(MyInt(10)); // 可以显式地调用构造函数
    return 0;
}

In the example above, the MyInt class has a single parameter constructor with the explicit keyword, meaning that an integer cannot be implicitly converted to a MyInt object. Only by explicitly calling the constructor can a MyInt object be created. In the main function, it can be seen that it is incorrect to call the printInt function with implicit conversion, but it is possible to pass a MyInt object to the printInt function by explicitly calling the constructor.

Leave a Reply 0

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