用c++写代码,代码为main.cpp,complex.cpp,complex.h,c(0,0),c1(3,5),c+=c1,c+=5,输出结果为c=c1+c2
时间: 2024-03-07 08:49:44 浏览: 139
complex.h:
```cpp
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex {
public:
Complex(double real = 0, double imag = 0);
double real() const;
double imag() const;
Complex& operator+=(const Complex& other);
Complex& operator+=(double real);
};
Complex operator+(const Complex& a, const Complex& b);
#endif
```
complex.cpp:
```cpp
#include "complex.h"
Complex::Complex(double real, double imag) : real_(real), imag_(imag) {}
double Complex::real() const {
return real_;
}
double Complex::imag() const {
return imag_;
}
Complex& Complex::operator+=(const Complex& other) {
real_ += other.real_;
imag_ += other.imag_;
return *this;
}
Complex& Complex::operator+=(double real) {
real_ += real;
return *this;
}
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real_ + b.real_, a.imag_ + b.imag_);
}
```
main.cpp:
```cpp
#include <iostream>
#include "complex.h"
using namespace std;
int main() {
Complex c(0, 0);
Complex c1(3, 5);
Complex c2(2, -1);
c = c1 + c2;
cout << "c = " << c.real() << " + " << c.imag() << "i" << endl;
return 0;
}
```
输出:
```
c = 5 + 4i
```
阅读全文