写一个程序:复数类Complex,使用友元函数完成复数的加法运算和复数的输出,并编程测试设计的类...
时间: 2024-01-22 07:19:28 浏览: 22
以下是实现复数类Complex的代码,其中包括友元函数和测试代码:
```C++
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
friend Complex operator+(Complex c1, Complex c2); // 友元函数
friend ostream& operator<<(ostream& os, Complex c); // 友元函数
};
Complex operator+(Complex c1, Complex c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
ostream& operator<<(ostream& os, Complex c) {
if (c.imag >= 0)
os << c.real << "+" << c.imag << "i";
else
os << c.real << c.imag << "i";
return os;
}
int main() {
Complex c1(1, 2), c2(3, -4), c3;
c3 = c1 + c2;
cout << c1 << " + " << c2 << " = " << c3 << endl;
return 0;
}
```
程序输出结果:
```
1+2i + 3-4i = 4-2i
```
以上代码中,复数类Complex包含两个私有成员变量real和imag,分别表示复数的实部和虚部。构造函数可以传入实部和虚部的初始值。友元函数operator+用于实现复数的加法运算,返回一个新的Complex对象。友元函数operator<<用于实现复数的输出,将复数以“实部+虚部i”的形式输出。测试代码中创建了三个Complex对象,分别进行加法运算和输出。