在C++中,std::complex
是一個模板類,用于表示復數。它已經為你提供了一系列運算符重載,例如+
、-
、*
和/
,以及相等和不等運算符。然而,如果你想要自定義一個復數類并實現這些運算符重載,以下是一個簡單的示例:
#include<iostream>
class Complex {
public:
Complex(double real, double imag) : real_(real), imag_(imag) {}
// Getters
double real() const { return real_; }
double imag() const { return imag_; }
// Operator overloads
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
Complex operator-(const Complex& other) const {
return Complex(real_ - other.real_, imag_ - other.imag_);
}
Complex operator*(const Complex& other) const {
double real_part = real_ * other.real_ - imag_ * other.imag_;
double imag_part = real_ * other.imag_ + imag_ * other.real_;
return Complex(real_part, imag_part);
}
Complex operator/(const Complex& other) const {
double denominator = other.real_ * other.real_ + other.imag_ * other.imag_;
double real_part = (real_ * other.real_ + imag_ * other.imag_) / denominator;
double imag_part = (imag_ * other.real_ - real_ * other.imag_) / denominator;
return Complex(real_part, imag_part);
}
bool operator==(const Complex& other) const {
return real_ == other.real_ && imag_ == other.imag_;
}
bool operator!=(const Complex& other) const {
return !(*this == other);
}
private:
double real_;
double imag_;
};
int main() {
Complex a(3, 4);
Complex b(1, 2);
Complex c = a + b;
Complex d = a - b;
Complex e = a * b;
Complex f = a / b;
std::cout << "a + b = (" << c.real() << ", " << c.imag() << ")\n";
std::cout << "a - b = (" << d.real() << ", " << d.imag() << ")\n";
std::cout << "a * b = (" << e.real() << ", " << e.imag() << ")\n";
std::cout << "a / b = (" << f.real() << ", " << f.imag() << ")\n";
return 0;
}
這個示例中的Complex
類實現了加法、減法、乘法和除法運算符重載。同時還實現了相等和不等運算符重載。注意,這里的運算符重載函數都是const
成員函數,因為它們不應該修改對象的狀態。