在C++中,運(yùn)算符重載允許你為自定義類型(如類或結(jié)構(gòu)體)定義運(yùn)算符的行為。要實(shí)現(xiàn)算術(shù)運(yùn)算符重載,你需要重載以下運(yùn)算符:
以下是一個(gè)簡(jiǎn)單的示例,展示了如何為一個(gè)名為MyNumber
的類實(shí)現(xiàn)這些運(yùn)算符重載:
#include <iostream>
class MyNumber {
public:
MyNumber(int value) : value_(value) {}
// 加法運(yùn)算符重載
MyNumber operator+(const MyNumber& other) const {
return MyNumber(value_ + other.value_);
}
// 減法運(yùn)算符重載
MyNumber operator-(const MyNumber& other) const {
return MyNumber(value_ - other.value_);
}
// 乘法運(yùn)算符重載
MyNumber operator*(const MyNumber& other) const {
return MyNumber(value_ * other.value_);
}
// 除法運(yùn)算符重載
MyNumber operator/(const MyNumber& other) const {
return MyNumber(value_ / other.value_);
}
// 取模運(yùn)算符重載
MyNumber operator%(const MyNumber& other) const {
return MyNumber(value_ % other.value_);
}
// 負(fù)數(shù)運(yùn)算符重載
MyNumber operator-() const {
return MyNumber(-value_);
}
// 正數(shù)運(yùn)算符重載
MyNumber operator+() const {
return MyNumber(value_);
}
// 輸出運(yùn)算符重載
friend std::ostream& operator<<(std::ostream& os, const MyNumber& number) {
os << number.value_;
return os;
}
private:
int value_;
};
int main() {
MyNumber a(5);
MyNumber b(3);
MyNumber c = a + b;
MyNumber d = a - b;
MyNumber e = a * b;
MyNumber f = a / b;
MyNumber g = a % b;
std::cout << "a + b = "<< c << std::endl;
std::cout << "a - b = "<< d << std::endl;
std::cout << "a * b = "<< e << std::endl;
std::cout << "a / b = "<< f << std::endl;
std::cout << "a % b = "<< g << std::endl;
return 0;
}
在這個(gè)示例中,我們定義了一個(gè)名為MyNumber
的類,它包含一個(gè)私有成員變量value_
。我們?yōu)檫@個(gè)類重載了加法、減法、乘法、除法、取模、負(fù)數(shù)和正數(shù)運(yùn)算符。此外,我們還重載了輸出運(yùn)算符(<<),以便在控制臺(tái)上打印MyNumber
對(duì)象。
在main
函數(shù)中,我們創(chuàng)建了兩個(gè)MyNumber
對(duì)象a
和b
,并使用重載的運(yùn)算符對(duì)它們進(jìn)行操作。最后,我們將結(jié)果輸出到控制臺(tái)。