c++ 定义一个复数类Complex,重载运算符+使之能够用于两个复数对象之和、复数类对象与浮点型数据之和的运算,如c1+c2,c1+i。
时间: 2024-03-01 16:54:06 浏览: 157
蓝桥杯国赛题之C++复数四则运算.zip
好的,以下是一个简单的Complex类的定义及运算符重载实现:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Complex operator+(double const &num) {
Complex res;
res.real = real + num;
res.imag = imag;
return res;
}
friend Complex operator+(double const &num, Complex const &obj) {
Complex res;
res.real = obj.real + num;
res.imag = obj.imag;
return res;
}
void print() {
cout << real << " + i" << imag << endl;
}
};
int main() {
Complex c1(2, 3), c2(4, 5);
Complex res1 = c1 + c2;
Complex res2 = c1 + 2.5;
Complex res3 = 1.5 + c2;
res1.print();
res2.print();
res3.print();
return 0;
}
```
在这个实现中,我们先定义了一个Complex类,其中包含了实部和虚部两个私有成员变量。接着,我们重载了运算符+,实现了两个复数对象之和和一个复数对象与浮点型数据之和的运算。同时,我们使用了友元函数来重载一个浮点型数据与复数对象之和的运算符。最后,我们在main函数中分别创建了两个复数对象和一个浮点数,在运算符重载的帮助下实现了不同的加法运算。
阅读全文