二元运算符重载;隐式类型转换 [英] 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
}
}
编译器说比较运算符是不明确的。编译器无法决定是否应将 / code> qualifer在第二个第二个参数,以摆脱歧义: 或使用显式 或使用不同的 a
转换为 bool
或 b
应转换为 my_bool
。有没有办法我可以解决这个问题没有写下3个重载( my_bool
, my_bool
), $ c> bool , my_bool
),( my_bool
, c>
friend my_bool operator == my_bool& instance_1,my_bool& instance_2);
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;
}
};
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);
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;
}
};
这篇关于二元运算符重载;隐式类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!