4

I'm kinda new to C++ and i got this problem while learning about it

So I have created this class

class A {
    int num;
public:
    //constructor
    A(int num) {
        this->num = num;
    }
    int getNum() {
        return num;
    }
    //overload <<
    friend ostream& operator << (ostream& os,A& a) {
        os << a.getNum();
        return os;
    }
};

In the main function, if I use cout<< A(1); it compiles wrong ( code C2679 in Visual Studio 2017 ).
How can I make it like cout<< int(1); ? Do I need to overload any other operator?

haccks
  • 104,019
  • 25
  • 176
  • 264
  • Possible duplicate of [How come a non-const reference cannot bind to a temporary object?](https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object) – Artyer May 07 '19 at 10:28

2 Answers2

4

Your overload needs to take a const A&, otherwise the anonymous temporary A(1) cannot bind to it.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

One more way is to overload the operator << with rvalue references

friend ostream& operator << (ostream& os, A&& a) {        
        os << a.getNum();
        return os;
    }
nayab
  • 2,332
  • 1
  • 20
  • 34