I know I can use a dummy int in the postfix operator++ as someClassObject.operator++(5)
, but why can't use it like someClassObject++5
? I am asking this because operator+
can be used like someClassObject1 + someClassObject2
.
{
public:
test(int x, string y) : x(x), y(y){}
test() :x(0), y("") {};
//skiping some code for copy constructor and assignment operator overload
test operator++(int x)
{
test a(*this);
a.x += x;
++(*this);
return a;
}
friend ostream& operator<<(ostream& ost, const test& test)
{
ost << test.x << " , " << test.y;
return ost;
}
int x;
string y;
};
int main()
{
test t1(5, "testing");
int x = 10;
cout << t1.operator++(x) << endl;
//the above line of code works but the line below gives error.
t1++x;
return 0;
}
I was expecting both t1.operator++(5)
and t1++5
would work in the same way.
You're not allowed to overload functions purely by return type, so a dummy parameter is necessary to differentiate between two identical looking operator++() operators.
The dummy parameter is simply there to distinguish between the postfix and prefix operators. The name ++ or -- is the same in both cases, so there has to be some way to specify which one you're defining.
The compiler uses the int argument to distinguish between the prefix and postfix increment operators.
The int parameter is a dummy parameter used to differentiate between prefix and postfix versions of the operators. When the user-defined postfix operator is called, the value passed in that parameter is always zero, although it may be changed by calling the operator using function call notation (e.g., a.
Due to the maximal munch rule, the expression
t1++x
is parsed as
t1 ++ x
and grouped as
(t1 ++) x
This makes no sense; rather like t1 x
makes no sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With