I have question, what does it mean to return an assignment expression like in my code example? I have an enum, and i have override the ++:operator. So it is possible to switch between ligths in my short example - but there is a part in the code i dont understand. The code compiles and work fine.
Code:
enum Traficlight
{green, yellow, red };
Traficlight& operator++(Traficlight& t)
{
switch (t)
{
case green: return t = Traficlight::yellow; //Here <--
case yellow: return t = Traficlight::red; //Here <--
case red: return t = Traficlight::green; //Here <--
default:
break;
}
}
int main()
{
Traficlight Trafic = Traficlight::green;
Trafic++;
if (Trafic == Traficlight::yellow)
{
cout << "Light is Yellow" << endl;
}
string in;
cin >> in;
}
What does the "return t = Traficlight::yellow" mean, why cant i just return "Traficlight::yellow".
symbols “=” and “<-” are used as the assignment operator.
The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.
The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.
The simple assignment operator ( = ) is used to assign a value to a variable.
In the return instructions, the operator assigns to t
which is a reference (modifies it) then returns the value.
That's what an incrementation operator does: modifies & returns reference at the same time so the incremented value can be used in another operation.
t = Traficlight::yellow
writes Traficlight::yellow
into t
. The result of that expression is also Traficlight::yellow
, so this:
return t = Traficlight::yellow;
is equal to:
t = Traficlight::yellow;
return t;
In the function above, reference to t
was received as argument, so changing value of t
is in fact relevant.
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