6. 定义一个复数类Complex,重载运算符“-”,使之能用于复数的减法运算。将运算符函数重载为非成员、非友元的普通函数。编写程序,求两个复数之差。
时间: 2024-02-11 07:06:50 浏览: 66
好的,这个问题简单,以下是重载运算符“-”后的Complex类的定义和示例程序:
```
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0) {
m_real = real;
m_imag = imag;
}
double real() const { return m_real; }
double imag() const { return m_imag; }
private:
double m_real;
double m_imag;
};
Complex operator- (const Complex& c1, const Complex& c2) {
Complex result;
result = Complex(c1.real() - c2.real(), c1.imag() - c2.imag());
return result;
}
#include <iostream>
using namespace std;
int main() {
Complex c1(3.0, 4.5);
Complex c2(1.5, 2.0);
Complex c3 = c1 - c2;
cout << "c1 - c2 = " << c3.real() << " + " << c3.imag() << "i" << endl;
return 0;
}
```
执行输出结果为:
```
c1 - c2 = 1.5 + 2.5i
```
阅读全文