在函数重载声明时,可以使用explicit关键字来显式地定义参数类型,避免隐式类型转换造成重载模糊。例如:
#include
using namespace std;
class MyClass {
public:
void print(int value) {
cout << "int:" << value << endl;
}
void print(double value) {
cout << "double:" << value << endl;
}
void print(const char* value) {
cout << "string:" << value << endl;
}
};
int main() {
MyClass obj;
obj.print(10); // int:10
obj.print(3.14); // double:3.14
obj.print("hello"); // string:hello
obj.print(static_cast(3.14)); // int:3 (显式类型转换)
return 0;
}
在这个示例中,用到了三个函数重载分别处理int、double和const char*类型的参数。如果不使用explicit关键字,当输入一个浮点数时,C++会自动地将它转换成int,这样就无法调用第二个print函数了。因此,我们可以使用explicit关键字来避免这个问题:
#include
using namespace std;
class MyClass {
public:
void print(int value) {
cout << "int:" << value << endl;
}
void print(double value) {
cout << "double:" << value << endl;
}
void print(const char* value) {
cout << "string:" << value << endl;
}
};
class MyInt {
public:
explicit MyInt(int value) : m_value(value) {}
operator int() const { return m_value; }
private:
int m_value;
};
int main() {
MyClass obj;
obj.print(10); // int:10
obj.print(3.14); // double:3.14
obj.print("hello"); // string:hello
obj.print(static_cast(3.14)); // int