复数类设计: (1)数据:实部(real)、虚部(imag) (2)操作:构造函数、get、set、print、运算符重载(加法、减法、++) 在此基础上增加对赋值运算符=的重载
时间: 2023-06-19 07:07:28 浏览: 121
以下是C++的复数类设计,包括构造函数、get、set、print、运算符重载(加法、减法、++)和赋值运算符=的重载:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex() : real(0), imag(0) {} // 默认构造函数
Complex(double r, double i) : real(r), imag(i) {} // 带参数构造函数
double getReal() const { return real; } // 获取实部
double getImag() const { return imag; } // 获取虚部
void setReal(double r) { real = r; } // 设置实部
void setImag(double i) { imag = i; } // 设置虚部
void print() const { // 输出复数
if (imag >= 0) cout << real << " + " << imag << "i" << endl;
else cout << real << " - " << -imag << "i" << endl;
}
Complex operator+(const Complex& other) const { // 加法运算符重载
double r = real + other.real;
double i = imag + other.imag;
return Complex(r, i);
}
Complex operator-(const Complex& other) const { // 减法运算符重载
double r = real - other.real;
double i = imag - other.imag;
return Complex(r, i);
}
Complex operator++() { // 前置++运算符重载
++real;
++imag;
return *this;
}
Complex& operator=(const Complex& other) { // 赋值运算符=重载
if (this != &other) {
real = other.real;
imag = other.imag;
}
return *this;
}
};
int main() {
Complex a(2, 3);
Complex b(4, -5);
Complex c = a + b;
c.print(); // 输出6 - 2i
++c;
c.print(); // 输出7 - 1i
a = c;
a.print(); // 输出7 - 1i
return 0;
}
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)