Jua*_*uel 1 c++ operator-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;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试编译时,我得到了.
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)))))'
Run Code Online (Sandbox Code Playgroud)
提前致谢
编辑:实施:
#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;
}
Run Code Online (Sandbox Code Playgroud)
还修改,我将参数更改为const:
friend ostream& operator << (ostream &tmp, Cmplx const ¶m)
{
tmp<<param.Re<<"+"<<param.Im<<"i";
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
还是行不通
编辑2:我打破了cout线,发现问题是我班上的一对方法,实际上并没有使用'+'运算符.我仍然不知道为什么,但至少我可以编译.
另外,我想知道我是否可以为我的班级获得特定的风格输入,我的意思是
scanf("%d+%di",Re,Im);
Run Code Online (Sandbox Code Playgroud)
但是使用cin(我不能,或者至少我不知道如何使用,scanf因为它是一个模板,为每种类型的数据写一个特定的cin是相当尴尬的)
编辑3:我发现了问题,缺少括号.
你没有展示你对它的使用,但在这种情况下,我可以看到它是什么.
你正在做类似的事情std::cout << (Cmplx1 + Cmplx2);.
结果(Cmplx1 + Cmplx2)是暂时的; 临时表达式可能不会绑定到引用.
例如:
int f() {
return 3;
}
int& x = f(); // ill-formed
Run Code Online (Sandbox Code Playgroud)
然而,作为一个特殊的C++魔术,临时工可以绑定到references-to-const:
例如:
int f() {
return 3;
}
int const& x = f(); // magic!
Run Code Online (Sandbox Code Playgroud)
临时然后生活就像reference-to-const那样.
如果操作员接受对const复杂对象的引用,则可以将临时绑定为第二个参数:
friend ostream& operator<<(ostream& os, Cmplx const& param)
{
os << param.Re << "+" << param.Im << "i";
return os;
}
Run Code Online (Sandbox Code Playgroud)
方便的是,你应该首先做到这一点,因为你不会修改param(并且,在一个operator<<,永远不应该).
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
402 次 |
| 最近记录: |