C++ 模板运算符重载无法绑定非常量左值引用

C++ 模板运算符重载无法绑定非常量左值引用,c++,templates,operator-overloading,friend,C++,Templates,Operator Overloading,Friend,我尝试过const和passing by reference的变体,但似乎每个走廊都有问题。 此配置导致错误,无法将类型为“thingArr&”的非常量左值引用绑定到类型为“thingArr”的右值 我做错了什么 #include <iostream> using namespace std; template <typename T> class thingArr { public: thingArr(){for(int i=0;i<4;++i)n[i] =

我尝试过const和passing by reference的变体,但似乎每个走廊都有问题。 此配置导致错误,无法将类型为“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;
}
#包括
使用名称空间std;
模板
类thingArr
{
公众:

thingArr(){for(inti=0;i多亏了S.M.,我有了一个工作版本:

#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;
}
#包括
使用名称空间std;
模板
类thingArr
{
公众:

thingArr(){for(int i=0;iWhy not
const thingArr&mIn
在args中?这会导致错误“将'thingArr&'类型的引用绑定到'const thingArr'会丢弃限定符”在第16行,
const thingArr
从哪里来?我在你的代码中看不到它。然后返回
。啊!好的,一条线索。谢谢你,S.M.!这似乎有效:``` class thingArr{public:thingArr(){for(int I=0;我为什么不
const thingArr&M
在args?和
std::ostream&operator