定义一个复数类,重载“-=”运算符,使这个运算符能直接完成复数的“-=”运算。分别用成员函数与友元函数编写运算符重载函数。在主函数中定义复数对象c1(10,20)、c2(15,30),进行c2-=c1的复数运算,并输出c1、c2的复数值。
时间: 2024-05-08 08:16:37 浏览: 22
复数类(包括运算符重载)
```C++
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
void print() { cout << real << '+' << imag << 'i' << endl; }
Complex operator-=(const Complex& c); // 成员函数重载
friend Complex operator-=(Complex& c1, const Complex& c2); // 友元函数重载
private:
double real, imag;
};
Complex Complex::operator-=(const Complex& c) {
real -= c.real;
imag -= c.imag;
return *this;
}
Complex operator-=(Complex& c1, const Complex& c2) {
c1.real -= c2.real;
c1.imag -= c2.imag;
return c1;
}
int main() {
Complex c1(10, 20), c2(15, 30);
c2 -= c1;
c1.print();
c2.print();
return 0;
}
```
阅读全文