lundi 14 mai 2018

Operator overloading c++ explanation

I am trying to understand an output of a short program, where operator overloading is used. The output is 137, where the (2+v).print() outputs 13 and 7 is from v.print();

#include <iostream>
using namespace std;
class V {
 int x;
public:
 V(int a=7, int b=3) { x = a + b; }
 void print() { cout << x;}
 V operator+(int n) {
 return x++ + ++n;
}
};
V operator+(int lop, V rop) {
 return rop + lop;
}
int main()
{
 V v(1,6); 
 (2 + v).print();  
 v.print();
 return 0;
}

I understand the basic concept of the operator overloading and I get that V rop is just a copy of the V v(1,6), and it doesn't change the output of v.print(); where x stays 7, but I don't get why it outputs 13, I always get to 10.

Thank you very much for helping me out!

Aucun commentaire:

Enregistrer un commentaire