我正在尝试在 C++ 中实现一个类 COMPLEX 并重载算术运算符以及用于输入/输出的 '<<' 和 '>>' 运算符。单独和级联算术运算符按预期工作 - 但是在尝试执行以下语句时我无法获得正确的结果:
cout << "something" << complex1 + complex2 << "\n";
其中 complex1 和 complex2 是 COMPLEX 类的对象。
类定义的片段:
class COMPLEX{
int a; // Real part
int b; // Imaginary part
public:
COMPLEX operator = (COMPLEX );
COMPLEX operator + (COMPLEX ) const;
friend istream& operator >> (istream &, COMPLEX &);
friend ostream& operator << (ostream &, COMPLEX &);
-snip-
}
COMPLEX COMPLEX::operator = (COMPLEX t_c) {
return COMPLEX(a = t_c.a, b = t_c.b);
}
COMPLEX COMPLEX::operator + (COMPLEX t_c) const{
return COMPLEX(a + t_c.a, b + t_c.b);
}
istream& operator >> (istream &i_s, COMPLEX &t_c){
i_s >> t_c.a >> t_c.b;
return i_s;
}
ostream& operator << (ostream &o_s, COMPLEX &t_c){
o_s << t_c.a << "+" << t_c.b << "i";
return o_s;
}
除此之外,我还重载了运算符。
当我尝试将 << 与任何其他重载运算符级联时,重载的 << 友元函数不会被调用。相反,操作员被调用并显示结果。