重载加法运算符以将两个复数相加的 C++ 程序
假设我们有一个带有实部和虚部的复数类。我们必须重载加法(+)运算符才能将两个复数相加。我们还必须定义一个函数来以正确的表示形式返回复数。
所以,如果输入像c1=8-5i,c2=2+3i,那么输出将是10-2i。
示例
让我们看看以下实现以获得更好的理解-
#include#include #include 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)
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下