用运算符重载设计复数类,实现复数的+、-、*、/运算。
时间: 2024-05-07 14:20:45 浏览: 113
好的,我可以给您提供一个样例代码:
```c++
#include<iostream>
using namespace std;
class Complex{
public:
Complex(){
real = 0;
imag = 0;
}
Complex(double r, double i){
real = r;
imag = i;
}
Complex operator+(const Complex& c2){
Complex temp(real+c2.real, imag+c2.imag);
return temp;
}
Complex operator-(const Complex& c2){
Complex temp(real-c2.real, imag-c2.imag);
return temp;
}
Complex operator*(const Complex& c2){
Complex temp(real*c2.real - imag*c2.imag, real*c2.imag + imag*c2.real);
return temp;
}
Complex operator/(const Complex& c2){
double denominator = c2.real*c2.real + c2.imag*c2.imag;
Complex temp((real*c2.real + imag*c2.imag)/denominator, (imag*c2.real - real*c2.imag)/denominator);
return temp;
}
friend ostream& operator<<(ostream& os, const Complex& c);
private:
double real;
double imag;
};
ostream& operator<<(ostream& os, const Complex& c){
os << c.real << "+" << c.imag << "i";
return os;
}
int main(){
Complex c1(2.0, 3.0);
Complex c2(4.0, 5.0);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
Complex c6 = c1 / c2;
cout << c1 << "+" << c2 << "=" << c3 << endl;
cout << c1 << "-" << c2 << "=" << c4 << endl;
cout << c1 << "*" << c2 << "=" << c5 << endl;
cout << c1 << "/" << c2 << "=" << c6 << endl;
return 0;
}
```
在这个例子中,我们定义了一个 Complex 类,包含了两个私有成员变量 real 和 imag,分别表示复数的实部和虚部。然后我们重载了 +、-、*、/ 四个运算符,实现了复数的加减乘除运算。我们还重载了输出运算符 <<,方便输出复数对象。最后在 main 函数中测试了我们定义的运算符重载是否正确。
阅读全文