'<<' & '>>' 运算符重载

'<<' & '>>' operators overloading

本文关键字:gt lt 重载 运算符      更新时间:2023-10-16

我一直在为一个学校班级从头开始写一个复数标题,但我被提取和插入运算符过载所困扰,我读了很多关于这个主题的文章,但我仍然不明白

friend ostream& operator << (ostream &tmp, Cmplx &param)
{
    tmp<<param.Re<<"+"<<param.Im<<"i";
    return tmp;
}
friend istream& operator >> (istream &tmp, Cmplx &param)
{
    tmp>>param.Re;
    tmp>>param.Im;
    return tmp;
}

但当我尝试编译时,我得到了。

no match for 'operator<<' in 'std::cout << Cmplx<vartype>::operator+(Cmplx<vartype>) [with vartype = long double](Cmplx<long double>(((const Cmplx<long double>&)((const Cmplx<long double>*)(& B)))))'

提前感谢

编辑:实施:

#include"cmplx oper.hpp"
using namespace std;
int main()
{
Cmplx<long double> A, B;
cin >> A;
cin >> B;
cout<<(A+B)<<(A-B)<<(A*B)<<(A/B)<<(A+B).norm<<(A+B).pol<<(A+B).conj<<(A+B).re<<(A+B).im<<endl;
getch();
return true;
}

还有修改,我把参数改为const:

friend ostream& operator << (ostream &tmp, Cmplx const &param)
{
    tmp<<param.Re<<"+"<<param.Im<<"i";
    return tmp;
}

仍然不工作

编辑2:我分解了cout行,发现问题出在我的类中的两个方法上,而实际上不是使用了"+"运算符。我仍然不知道为什么,但至少我可以编译。

此外,我想知道我是否可以为我的课程获得特定的风格输入,我的意思是类似的东西

scanf("%d+%di",Re,Im);

但是使用cin(我不能,或者至少我不知道如何使用scanf,因为它是一个模板,为每种类型的数据编写特定的cin非常尴尬)

编辑3:我发现了问题,缺少括号。

您没有展示您对它的使用,但在这种情况下,我可以看到发生了什么。

你正在做类似std::cout << (Cmplx1 + Cmplx2);的事情。

(Cmplx1 + Cmplx2)的结果是暂时的;临时表达式不能绑定到引用。

例如:

int f() {
   return 3;
}
int& x = f(); // ill-formed

然而,作为C++魔术的一个特殊部分,临时性可以绑定到references-to-const:

例如:

int f() {
   return 3;
}
int const& x = f(); // magic!

临时的寿命与reference-to-const一样长。

如果您的运算符引用const复杂对象,那么您可以绑定一个临时参数作为第二个参数:

friend ostream& operator<<(ostream& os, Cmplx const& param)
{
    os << param.Re << "+" << param.Im << "i";
    return os;
}

方便的是,您应该首先这样做,因为您不会修改param(而且,在operator<<中,永远不应该)。

希望能有所帮助。