- #include <iostream>
- using namespace std;
- class Complex {
- private:
- int real;
- int imag;
- public:
- Complex(int r = 0, int i = 0) : real(r), imag(i) {}
- Complex(const Complex& c) : real(c.real), imag(c.imag) {}
-
- void Display() {
- cout << real << (imag >= 0 ? "+" : "-") << abs(imag) << "i" << endl;
- }
-
- friend Complex AddComplex(const Complex& c1, const Complex& c2);
- };
- Complex AddComplex(const Complex& c1, const Complex& c2) {
- int r = c1.real + c2.real;
- int i = c1.imag + c2.imag;
- return Complex(r, i);
- }
- int main() {
- int x, y;
- cin >> x >> y;
- Complex c0(x, y);
- Complex c1(c0);
- c0.Display();
-
- cin >> x >> y;
- Complex c2(x, y);
- c2.Display();
-
- Complex c3 = AddComplex(c0, c2);
- c3.Display();
-
- return 0;
- }
复制代码
代码解析:
- 首先定义了一个Complex类,包含私有成员real(实部)和imag(虚部),默认值均为0。公有成员包括:带有默认形参值的构造函数、复制构造函数和Display函数。
- 接下来定义了一个友元函数AddComplex,用来实现两个复数相加。该函数传入两个复数类的常引用,返回一个新的Complex对象。
- 在主函数中,先读取两个整数作为第一个复数的实部和虚部,并创建一个对应的Complex对象c0。然后用c0初始化另一个Complex对象c1,并调用Display函数显示c0。
- 再次读取两个整数作为第二个复数的实部和虚部,并创建一个对应的Complex对象c2。然后调用Display函数显示c2。
- 最后,调用AddComplex函数将c0和c2相加,得到一个新的Complex对象c3,然后调用Display函数显示c3。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。