Increment and decrement operators

Posted by Didi Setyapramana On 8:40 PM 0 komentar

Increment and decrement operators

++ (increment)
— (decrement)

Increment and decrement have two forms, prefix (++i) and postfix (i++). To differentiate, the postfix version takes a dummy integer. Increment and decrement operators are most often member functions, as they generally need access to the private member data in the class. The prefix version in general should return a reference to the changed object. The postfix version should just return a copy of the original value. In a perfect world, A += 1, A = A + 1, A++, ++A should all leave A with the same value.

Example

SomeValue& SomeValue::operator++() // prefix

{

++data;

return *this;

}



SomeValue SomeValue::operator++(int unused) // postfix

{

SomeValue result = *this;

++data;

return result;

}


Often one operator is defined in terms of the other for ease in maintenance, especially if the function call is complex.

SomeValue SomeValue::operator++(int unused) // postfix

{

SomeValue result = *this;

++(*this);

// call SomeValue::operator++()

return result;

}

0 Response for the "Increment and decrement operators"

Post a Comment