0

I have tried variations of const and passing by reference, but seem to have problems down every corridor. 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?

#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;
}
  • 1
    Why not `const thingArr& mIn` in args? – 273K Dec 04 '19 at 06:26
  • that gives the error "binding reference of type ‘thingArr&’ to ‘const thingArr’ discards qualifiers" on line 16 – user1021810 Dec 04 '19 at 06:30
  • Where `const thingArr` comes from? I don't see it in your code. And just `return out`. – 273K Dec 04 '19 at 06:34
  • ah! ok, a lead. thank you S.M. ! this seems to work: ``` 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& m) { s<<"\n("< – user1021810 Dec 04 '19 at 06:39
  • 1
    Why not `const thingArr& m` in args? – 273K Dec 04 '19 at 06:40

1 Answers1

0

thanks to S.M., I have a working version:

#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;
}
  • And `std::ostream& operator << (std::ostream& s, const thingArr& m)`, you don't modify `m`to display it. – Jarod42 Dec 04 '19 at 10:37