c – 奇怪的运算符重载行为?

前端之家收集整理的这篇文章主要介绍了c – 奇怪的运算符重载行为?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Foo{
  5.  
  6. string _s;
  7. public:
  8. Foo(string ss){
  9. _s = ss;
  10. }
  11. Foo& operator=(bool b){
  12. cout << "bool" << endl;
  13. return *this;
  14. }
  15. Foo& operator=(const string& ss){
  16. cout << "another one" << endl;
  17. return *this;
  18. }
  19. };
  20.  
  21.  
  22. int main(){
  23.  
  24. Foo f("bar");
  25. f = "this";
  26. return 0;
  27.  
  28. }

我有重载=运算符.我期待f =“这个”;调用operator =(const string& ss)重载的语句.但事实并非如此.它调用operator =(bool b)重载.为什么?

解决方法

这个运算符operator =(const string& ss)需要转换用户定义的参数类型(const char *到std :: string),而bool版本没有,所以提供了更好的匹配:你得到了转换内置类型const char [5]到const char *到bool.

猜你在找的C&C++相关文章