二元运算符重载;隐式类型转换 [英] binary operator overloading; implicit type conversion

查看:94
本文介绍了二元运算符重载;隐式类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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
}
}

编译器说比较运算符是不明确的。编译器无法决定是否应将 a 转换为 bool b 应转换为 my_bool 。有没有办法我可以解决这个问题没有写下3个重载( my_bool my_bool ), $ c> bool , my_bool ),( my_bool c>

/ code> qualifer在第二个第二个参数,以摆脱歧义:

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

http://ideone.com/30VfO1



或使用显式

  explicit operator bool(); 

或使用不同的 == 这样更有意义:

  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


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. 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?

解决方案

Remove the const qualifer on the second second parameter to get rid of the ambiguity:

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

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

这篇关于二元运算符重载;隐式类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆