定义一个复数类complex,重载运算符,使之能用于复数的加、减、乘、除
时间: 2023-11-08 22:28:22 浏览: 92
#include <iostream>
using namespace std;
class complex {
private:
double real;
double imag;
public:
complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
// 加法运算符重载
complex operator+(complex &c) {
complex tmp;
tmp.real = real + c.real;
tmp.imag = imag + c.imag;
return tmp;
}
// 减法运算符重载
complex operator-(complex &c) {
complex tmp;
tmp.real = real - c.real;
tmp.imag = imag - c.imag;
return tmp;
}
// 乘法运算符重载
complex operator*(complex &c) {
complex tmp;
tmp.real = real * c.real - imag * c.imag;
tmp.imag = real * c.imag + imag * c.real;
return tmp;
}
// 除法运算符重载
complex operator/(complex &c) {
complex tmp;
double denominator = c.real * c.real + c.imag * c.imag;
tmp.real = (real * c.real + imag * c.imag) / denominator;
tmp.imag = (imag * c.real - real * c.imag) / denominator;
return tmp;
}
void display() {
cout << "(" << real << "," << imag << ")" << endl;
}
};
int main() {
complex c1(1, 2), c2(3, 4);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
complex c5 = c1 * c2;
complex c6 = c1 / c2;
c3.display();
c4.display();
c5.display();
c6.display();
return 0;
}
阅读全文