1. 定义一个复数类,请完成复数加运算、减运算、乘运算、除运算、以及赋值运算操作符的重载。
时间: 2023-08-15 09:04:31 浏览: 84
好的,以下是一个简单的复数类的定义,包括了加、减、乘、除、赋值运算符的重载:
```cpp
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
Complex operator+(const Complex& c2) const; // 加法运算符重载
Complex operator-(const Complex& c2) const; // 减法运算符重载
Complex operator*(const Complex& c2) const; // 乘法运算符重载
Complex operator/(const Complex& c2) const; // 除法运算符重载
Complex& operator=(const Complex& c2); // 赋值运算符重载
void print() const { cout << "(" << real << ", " << imag << ")"; }
private:
double real, imag;
};
Complex Complex::operator+(const Complex& c2) const {
return Complex(real + c2.real, imag + c2.imag);
}
Complex Complex::operator-(const Complex& c2) const {
return Complex(real - c2.real, imag - c2.imag);
}
Complex Complex::operator*(const Complex& c2) const {
return Complex(real * c2.real - imag * c2.imag, imag * c2.real + real * c2.imag);
}
Complex Complex::operator/(const Complex& c2) const {
double r = c2.real * c2.real + c2.imag * c2.imag;
return Complex((real * c2.real + imag * c2.imag) / r, (imag * c2.real - real * c2.imag) / r);
}
Complex& Complex::operator=(const Complex& c2) {
real = c2.real;
imag = c2.imag;
return *this;
}
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
c3.print(); // (4, 6)
Complex c4 = c1 - c2;
c4.print(); // (-2, -2)
Complex c5 = c1 * c2;
c5.print(); // (-5, 10)
Complex c6 = c1 / c2;
c6.print(); // (0.44, -0.08)
Complex c7;
c7 = c2;
c7.print(); // (3, 4)
return 0;
}
```
在这个例子中,我们用 `Complex` 类来表示复数,其中包含了实部 `real` 和虚部 `imag`。我们重载了加、减、乘、除、赋值运算符,使得我们可以方便地对复数进行运算。
阅读全文