[英]templated operator overloading cannot bind non-const lvalue reference
I have tried variations of const and passing by reference, but seem to have problems down every corridor.我尝试过 const 和通过引用传递的变体,但似乎在每个走廊上都有问题。 This configuration gives the error cannot bind non-const lvalue reference of type 'thingArr&' to an rvalue of type 'thingArr' what am I doing incorrectly?此配置导致错误无法将“thingArr&”类型的非常量左值引用绑定到“thingArr”类型的右值我做错了什么?
#include <iostream>
using namespace std;
template <typename T>
class thingArr
{
public:
thingArr(){for(int i=0;i<4;++i)n[i] = 1;}
thingArr(thingArr& mIn){for(int i=0; i<4; ++i)n[i]=mIn.n[i];}
friend std::ostream& operator << (std::ostream& s, thingArr<T>& m)
{
s<<"\n("<<m.n[0]<<", "<<m.n[1]<<", "<<m.n[2]<<", "<<m.n[3]<<")";
return s;
}
friend thingArr operator * (thingArr inThingArr, T inScalar)
{
thingArr out(inThingArr);
for(int i=0;i<4;++i)out.n[i]*=inScalar;
return thingArr(out);
}
T n[4];
};
main(){
thingArr<float> A;
thingArr<float> B;
B = A * .25;
cout <<"A: "<<A<<endl;
cout <<"B: "<<B<<endl;
}
thanks to SM, I have a working version:感谢 SM,我有一个工作版本:
#include <iostream>
using namespace std;
template <typename T>
class thingArr
{
public:
thingArr(){for(int i=0;i<4;++i)n[i] = 1;}
thingArr(const thingArr& mIn){for(int i=0; i<4; ++i)n[i]=mIn.n[i];}
friend std::ostream& operator << (std::ostream& s, thingArr<T>& m)
{
s<<"\n("<<m.n[0]<<", "<<m.n[1]<<", "<<m.n[2]<<", "<<m.n[3]<<")";
return s;
}
friend thingArr operator * (const thingArr& inThingArr, T inScalar)
{
thingArr out(inThingArr);
for(int i=0;i<4;++i)out.n[i]*=inScalar;
return thingArr(out);
}
T n[4];
};
main(){
thingArr<float> A;
thingArr<float> B;
B = A * .25;
cout <<"A: "<<A<<endl;
cout <<"B: "<<B<<endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.