1.定义
explicit
是 C++ 中的一个关键字,用来修饰 构造函数 或 类型转换运算符,避免它们在不明确的情况下被隐式调用,从而提升代码的可读性和安全性。
2.用于构造函数
默认情况下,单参数构造函数允许隐式类型转换。例如:
#include <iostream>
class Example {
public:
Example(int x) {//单参数构造函数
cout << "Constructor called with:" << x << endl;
}
};
int main() {
Example obj = 42;//隐式调用构造函数
return 0;
}
输出:Constructor called with: 42
这里,Example obj = 42;
隐式地调用了构造函数,将 int
类型转换为 Example
类型。
避免隐式转换
为避免这种隐式转换,可以在构造函数前加上 explicit
关键字:
#include<iostream>
class Example {
public:
explicit Example(int x) {
cout << "Constructor called with:" << x << endl;
}
};
int main() {
//Example obj = 42;不存在从int转换到Example的适当构造函数
Example obj2(42);
return 0;
}
3. 用于类型转换运算符
当定义类型转换运算符时,默认情况下允许隐式转换。例如:
#include <iostream>
class Example {
public:
operator int() const { // 类型转换运算符
return 42;
}
};
int main() {
Example obj;
int x = obj; // 隐式调用类型转换运算符
std::cout << x << std::endl; // 输出 42
return 0;
}
避免隐式转换
可以通过 explicit
禁止隐式调用类型转换运算符:
#include <iostream>
class Example {
public:
explicit operator int() const { // 显式类型转换
return 42;
}
};
int main() {
Example obj;
// int x = obj; // 错误,隐式转换被禁止
int y = static_cast<int>(obj); // 正确,显式转换
std::cout << y << std::endl; // 输出 42
return 0;
}
4.C++11的改进
在 C++11 及之后,explicit
可以用于 带多个参数 的构造函数(配合参数的默认值)。
#include <iostream>
class Example {
public:
explicit Example(int x, int y = 0) {
std::cout << "Constructor called with: " << x << " and " << y << std::endl;
}
};
int main() {
Example obj1(10); // 正确,显式调用
Example obj2 = {10, 20}; // 错误,禁止隐式调用
return 0;
}