繁体   English   中英

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

[英]c++ operator overloading logical opertors

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

我需要重载+,-和*运算符,但需要将其替换为逻辑运算符;例如,

“ +”应使用OR

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

我是否必须将某种if陈述置于过载中?

任何有关我该如何做的帮助?

谢谢

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

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

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

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

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

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

无法重载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

暂无
暂无

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

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