37 lines
782 B
C++
37 lines
782 B
C++
|
// 编写一个名为 Complex 的类,表示复数。重载加法运算符 + ,使其能够执行两个复数的加法操作。
|
||
|
#include <iostream>
|
||
|
#include <cstring>
|
||
|
#include <cstdlib>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
class Complex
|
||
|
{
|
||
|
private:
|
||
|
double real, imag; // 实部和虚部
|
||
|
|
||
|
public:
|
||
|
Complex(double real, double imag) : real(real), imag(imag) {}
|
||
|
Complex(const Complex &other) : real(other.real), imag(other.imag) {}
|
||
|
~Complex() {}
|
||
|
|
||
|
public:
|
||
|
Complex operator+(const Complex &other)
|
||
|
{
|
||
|
return Complex(real + other.real, imag + other.imag);
|
||
|
}
|
||
|
void show()
|
||
|
{
|
||
|
cout << real << " + " << imag << "i" << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
Complex c1(1, 2);
|
||
|
Complex c2(3, 4);
|
||
|
Complex c3 = c1 + c2;
|
||
|
c3.show(); // 4 + 6i
|
||
|
return 0;
|
||
|
}
|