简体   繁体   English

二元运算符重载; 隐式类型转换

[英]binary operator overloading; implicit type conversion

class my_bool {
  private:
    bool value;
  public:
    my_bool(bool value) : value(value) {}
    operator bool();

    friend my_bool operator==(const my_bool & instance_1, const my_bool & instance_2);
};

void main(){
  my_bool a = true;
  bool b = false;

  if(a == b){
    // do something
  }
}

The compiler says that comparison operator is ambiguous. 编译器说比较运算符是不明确的。 Compiler cannot decide whether a should be converted to bool or b should be converted to my_bool . 编译器无法决定是否应将a转换为boolb应转换为my_bool Is there a way I can solve this problem without writing down 3 overloads ( my_bool , my_bool ), ( bool , my_bool ), ( my_bool , bool ) of the same comparison operator? 有没有一种方法可以解决这个问题,而无需写下my_bool my_bool 3个重载( my_boolmy_bool ),( boolmy_bool ),( my_boolbool )?

Remove the const qualifer on the second second parameter to get rid of the ambiguity: 删除第二个参数上的const qualifer以消除歧义:

friend my_bool operator==(const my_bool & instance_1, my_bool & instance_2);

http://ideone.com/30VfO1 http://ideone.com/30VfO1

Or use explicit 或者使用显式

 explicit operator bool();

Or use a different == overload that make more sense like this: 或者使用不同的==重载,这样更有意义:

class my_bool
{
private:
    bool value;
public:
    my_bool(bool value) : value(value) {}
    operator bool() { return value; }

    bool operator == (bool val)
    {
        return this->value == val;
    }
};

http://ideone.com/fBaiKp http://ideone.com/fBaiKp

You could explicitly convert a to a bool 你可以明确地a转换为bool

  if(((bool) a) == b){ // yes, this is a cast.
      // do something
  } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM