explicit
是 C++ 语言中的一个关键字,它可以用来修饰单个参数的构造函数,表示该构造函数只能显式调用,禁止隐式转换。在 C++11 中,explicit
还可以用来修饰类型转换函数,表示只能显式进行类型转换。
下面是一个简单的示例,演示了 explicit
的使用:
#include <iostream>
using namespace std;
class A {
public:
A(int x) : m_x(x) {}
int get_x() const { return m_x; }
private:
int m_x;
};
class B {
public:
explicit B(int x) : m_x(x) {}
int get_x() const { return m_x; }
private:
int m_x;
};
void funcA(A a) {
cout << "a.get_x() = " << a.get_x() << endl;
}
void funcB(B b) {
cout << "b.get_x() = " << b.get_x() << endl;
}
int main() {
A a1 = 1;
funcA(a1); // 可以隐式转换
// A a2 = 'a'; // 错误:不允许隐式转换
B b1 = 2;
// funcB(b1); // 错误:只能显式转换
funcB(static_cast<B>(3)); // 正确:显式转换
return 0;
}
在上面的示例中,我们定义了两个类 A
和 B
,它们都有一个 int 类型的成员变量 m_x
,并且分别定义了一个单个参数的构造函数。A
的构造函数没有使用 explicit
关键字,因此可以隐式转换。而 B
的构造函数使用了 explicit
关键字,只能显式转换。
在 main
函数中,我们分别创建了 A
和 B
的对象,并调用了 funcA
和 funcB
两个函数。其中,funcA
可以接受隐式转换,因此可以直接传递 a1
,而 funcB
只能接受显式转换,因此需要使用 static_cast
来进行类型转换。
总之,explicit
可以有效地防止隐式转换带来的意外结果,提高代码的可读性和安全性。