用 C++ 程序重载加法运算符以加两个复数
假设我们有一个带实部和虚部的复数类。我们需要对加法(+)运算符进行重载,以便加两个复数。我们还必须定义一个函数,以适当的表示形式返回复数。
因此,如果输入类似于 c1 = 8 - 5i,c2 = 2 + 3i,则输出将为 10 - 2i。
为了解决这个问题,我们将遵循以下步骤 −
重载 + 运算符并将另一个复数 c2 作为参数
定义一个名为 ret 的复数,其实部和虚部为 0
ret 的实部 := 自己的实部 + c2 的实部
ret 的虚部 := 自己的虚部 + c2 的虚部
返回 ret
示例
让我们看看以下实现,以便更好地理解 −
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(){
real = imag = 0;
}
Complex (int r, int i){
real = r;
imag = i;
}
string to_string(){
stringstream ss;
if(imag >= 0)
ss << "(" << real << " + " << imag << "i)";
else
ss << "(" << real << " - " << abs(imag) << "i)";
return ss.str();
}
Complex operator+(Complex c2){
Complex ret;
ret.real = real + c2.real;
ret.imag = imag + c2.imag;
return ret;
}
};
int main(){
Complex c1(8,-5), c2(2,3);
Complex res = c1 + c2;
cout << res.to_string();
}
输入
c1(8,-5), c2(2,3)
输出
(10 - 2i)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP