0

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

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

"+" 应该使用 OR

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

我是否必须在重载中添加某种 if 语句?

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

谢谢

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

4

3 回答 3

1

不需要if语句,只需要返回&&and的结果即可||

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

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

于 2012-04-17T10:55:22.013 回答
1

您不想为整数或任何其他内置类型重载这些运算符,对吗?因为这是不可能的。如果您有自己的包含布尔值或整数值的类,则逻辑如下所示:

bool operator + (const MyClass& m1, const MyClass& m2) 
{
     return m1.GetMyBooleanMember() || m2.GetMyBooleanMember();
} 
于 2012-04-17T10:55:51.920 回答
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
于 2012-04-17T10:56:04.717 回答