在C++中,可以通過定義成員函數或非成員函數來實現運算符重載。以下是一些示例代碼:
class Complex {
private:
double real;
double imaginary;
public:
Complex(double r, double i) : real(r), imaginary(i) {}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imaginary + other.imaginary);
}
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex result = c1 + c2;
return 0;
}
class Number {
private:
int value;
public:
Number(int v) : value(v) {}
Number& operator++() {
value++;
return *this;
}
};
int main() {
Number num(5);
++num;
return 0;
}
#include <iostream>
class Complex {
private:
double real;
double imaginary;
public:
Complex(double r, double i) : real(r), imaginary(i) {}
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << " + " << c.imaginary << "i";
return os;
}
};
int main() {
Complex c(1, 2);
std::cout << c << std::endl;
return 0;
}
需要注意的是,運算符重載一般應該符合運算符的原有語義,遵循常規的運算符規則,并不應該引入令人困惑的行為。