简体   繁体   中英

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

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?

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 || .

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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