'<<' & '>>' 运算符重载
'<<' & '>>' operators overloading
我一直在为一个学校班级从头开始写一个复数标题,但我被提取和插入运算符过载所困扰,我读了很多关于这个主题的文章,但我仍然不明白
friend ostream& operator << (ostream &tmp, Cmplx ¶m)
{
tmp<<param.Re<<"+"<<param.Im<<"i";
return tmp;
}
friend istream& operator >> (istream &tmp, Cmplx ¶m)
{
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 ¶m)
{
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<<
中,永远不应该)。
希望能有所帮助。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中