重载加法运算符以将两个复数相加的 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)
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短