c ++运算符重载逻辑运算符

时间:2012-04-17 10:50:41

标签: c++ operator-overloading logical-operators

嗨,我想知道如何解决这个问题,

我需要重载+, - 和*运算符,但需要用逻辑运算符替换它们,例如;

“+”应使用OR

0 + 0 = 0,0 + 1 = 1,1 + 1 = 1,1 + 0 = 1

我是否必须在过载中放置某种if语句?

关于我如何做到这一点的任何帮助?

由于

他们将使用二进制作为数据类型,两个矩阵以二进制作为数据

3 个答案:

答案 0 :(得分:1)

不需要if语句,您只需要返回&&||的结果。

struct A
{
   bool val;
   bool operator + (const A& other) { return val || other.val; }
   bool operator * (const A& other) { return val && other.val; }
};

请注意,您不能为内置类型重载运算符。至少有一个参数必须是用户定义的。

答案 1 :(得分:1)

您不希望为整数或任何其他内置类型重载这些运算符吗?因为这是不可能的。如果你有自己的类包含一个布尔值或整数值,那么逻辑就像这样:

bool operator + (const MyClass& m1, const MyClass& m2) 
{
     return m1.GetMyBooleanMember() || m2.GetMyBooleanMember();
} 

答案 2 :(得分:1)

重载operator +(int,int)是不可能的,但是你可以创建一个包装int并具有你想要的行为的新类型......

struct BoolInt
{
   int i;
};

BoolInt operator+(BoolInt x, BoolInt y) { return { x.i || y.i }; }
BoolInt operator*(BoolInt x, BoolInt y) { return { x.i && y.i }; }
BoolInt operator-(BoolInt x, BoolInt y) { return { x.i || !y.i }; } // guessing