运算符重载,遇到了这些问题
程序代码:
#include<iostream> using namespace std; class Complex { double real; double image; public: Complex(double r = 0, double i = 0) { real = r; image = i; } friend void inputcomplex(Complex &comp1, Complex &comp2); friend Complex addcomplex(Complex c1, Complex c2); friend void outputcomplex(Complex comp); }; void inputcomplex(Complex &comp1, Complex &comp2) { char op, ab,p; cin >> comp1.real >> op >> comp1.image >> p>> p >>comp2.real >> ab >> comp2.image >> p; if (op == '-',ab=='-') comp1.image = -comp1.image; comp2.image = -comp2.image; } Complex addcomplex(Complex c1, Complex c2) { Complex c; c.real = c1.real + c2.real; c.image = c1.image + c2.image; return c; } void outputcomplex(Complex comp) { cout << comp.real << ((comp.image >= 0) ? "+" : "") << comp.image << "i"; } int main() { Complex c1, c2, result; inputcomplex(c1, c2); result = addcomplex(c1, c2); outputcomplex(result); cout << endl; }
提交上去之后是:
这个程序存在一个如果我虚部等于1,那么就会变成这样的问题:
我该如何修改?