- #include <iostream>
- using namespace std;
- class Foo{
- string _s;
- public:
- Foo(string ss){
- _s = ss;
- }
- Foo& operator=(bool b){
- cout << "bool" << endl;
- return *this;
- }
- Foo& operator=(const string& ss){
- cout << "another one" << endl;
- return *this;
- }
- };
- int main(){
- Foo f("bar");
- f = "this";
- return 0;
- }
我有重载=运算符.我期待f =“这个”;调用operator =(const string& ss)重载的语句.但事实并非如此.它调用operator =(bool b)重载.为什么?
解决方法
这个运算符operator =(const string& ss)需要转换用户定义的参数类型(const char *到std :: string),而bool版本没有,所以提供了更好的匹配:你得到了转换内置类型const char [5]到const char *到bool.