在C++中,std::complex
是一个模板类,用于表示复数。它已经为你提供了一系列运算符重载,例如+
、-
、*
和/
,以及相等和不等运算符。然而,如果你想要自定义一个复数类并实现这些运算符重载,以下是一个简单的示例:
#include
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
成员函数,因为它们不应该修改对象的状态。