简体   繁体   English

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

[英]c++ operator overloading logical opertors

Hi I was wondering how I could tackle this problem, 嗨,我想知道如何解决这个问题,

I need to overload +, - and * operators but need to replace them with Logical operators for example; 我需要重载+,-和*运算符,但需要将其替换为逻辑运算符;例如,

"+" should use OR “ +”应使用OR

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

would i have to place in the overload some sort of if statment? 我是否必须将某种if陈述置于过载中?

Any help on how i could do this? 任何有关我该如何做的帮助?

Thanks 谢谢

They will being using binary as the data type, two matrices with binary as their data 他们将使用二进制作为数据类型,使用两个矩阵作为二进制数据

There's no need for an if statement, you just need to return the result of && and || 不需要if语句,只需要返回&&||的结果。 .

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

Note that you can't overload operators for built-in types. 请注意,您不能为内置类型重载运算符。 At least one of the arguments must be user-defined. 至少一个自变量必须是用户定义的。

You don't want to overload those operators for integers, or any other built-in types, do you? 您不想为整数或任何其他内置类型重载这些运算符,对吗? Because it's impossible. 因为那是不可能的。 If you have your own class which contains a boolean or integer value then the logic goes something like this: 如果您有自己的包含布尔值或整数值的类,则逻辑如下所示:

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

Overloading operator+(int, int) is not possible, however you can create a new type that wraps an int and has the behavior you want... 无法重载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