我对 C++ 重载函数数学感到困惑。 请参阅下面的代码:
#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 ..
对于调用
d.func("biancheng");
,打印的结果与func(bool)函数定义匹配。有人可以帮助我了解原因是什么吗?
我认为这将是 func(const string &s) 或 func(const string &&s) 之一。
"biancheng"
属于 char const[10]
类型。它衰减到char const*
。从这里开始有两种可能的转换。有到 bool
的隐式(内置)转换和到类类型 std::basic_string<char, /*char-traits-type and allocator*/>
的隐式转换。到类类型的转换始终被视为after内置转换,因此编译器在此处选择指向bool
转换的指针。
在您的代码中,当您调用函数
d.func("biancheng");
时,它与d.func(bool b)
匹配,因为字符串参数“bian Cheng”可以隐式转换为TRUE [布尔参数]。因此,调用了 d.func(bool b)
而不是 d.func(const string &s)
|| d.func(const string &&s)
。