Pra*_*are 7 c++ operator-overloading
#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;
}
Run Code Online (Sandbox Code Playgroud)
我有重载=运算符.我期望f = "this";声明调用operator=(const string& ss)重载.但事实并非如此.它叫operator=(bool b)过载.为什么?
jua*_*nza 13
此运算符operator=(const string& ss)需要转换参数(const char*to std::string)的用户定义类型,而bool版本没有,因此提供了更好的匹配:您可以获得从内置类型const char[5]到的const char*转换bool.
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |