簡體   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