复数类设计: (1)数据:实部(real)、虚部(imag) (2)操作:构造函数、get、set、print、运算符重载(加法、减法、++) 在此基础上增加对赋值运算符=的重载
时间: 2023-06-19 07:07:27 浏览: 213
下面是一个基本的复数类设计,满足上述要求:
```cpp
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r = 0.0, double i = 0.0) {
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 {
cout << real << " + " << imag << "i" << endl;
}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator++(int) {
Complex temp(*this);
real++;
imag++;
return temp;
}
Complex& operator=(const Complex& other) {
real = other.real;
imag = other.imag;
return *this;
}
};
```
其中,构造函数用于初始化实部和虚部;get、set、print 函数分别用于获取、设置和打印实部和虚部;运算符重载包括加法、减法和后置自增;赋值运算符重载用于将一个复数对象赋值给另一个复数对象。
阅读全文
相关推荐
![](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://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)