C++重载函数匹配疑问:字符串字面量为何匹配func(bool)?
C++重载函数匹配疑惑解析
问题说明
调用d.func("biancheng");时,实际匹配了func(bool)函数,但预期应该匹配func(const string &)或func(const string &&),以下是对应代码及运行结果:
示例代码
#include <iostream> using namespace std; class Base { public: void func(); void func(int); }; void Base::func() { cout << "Base::func()" << endl; } void Base::func(int a) { cout << "Base::func(int)" << endl; } class Derived : public Base { public: void func(const string &); void func(const string &&); void func(bool); }; void Derived::func(const string &s) { cout << "Derived::func(string &)" << endl; } void Derived::func(const string &&s) { cout << "Derived::func(string &&)" << endl; } void Derived::func(bool b) { cout << "Derived::func(bool)" << endl; } int main() { Derived d; d.func("biancheng"); d.func(false); // d.func(1); // d.Base::func(1); cout << endl << "completed .." << endl; return 0; }
运行结果
Derived::func(bool) Derived::func(bool) completed ..
原因解析
这个现象是名字隐藏和隐式转换优先级共同作用的结果:
- 名字隐藏:派生类
Derived中的func函数会隐藏基类Base里的所有同名函数,但此问题的核心是派生类自身的重载匹配逻辑。 - 隐式转换优先级:字符串字面量
"biancheng"属于const char[]类型,要匹配func(const string &)或func(const string &&),需要通过string的构造函数完成一次用户自定义转换;而const char[]可以直接隐式转换为bool(非空指针会转为true),这是内置类型的标准转换。在C++的重载决议规则中,标准转换的优先级高于用户自定义转换,因此编译器会优先选择func(bool)。
如果希望字符串字面量匹配string版本的重载,可以采取以下方式:
- 显式转换为
string:d.func(string("biancheng")); - 给派生类新增
const char*版本的func,避免隐式转换到bool
内容的提问来源于stack exchange,提问作者sanren1024
相关产品推荐
相关产品推荐

