Re: l-values and r-values
Ali Karaali wrote:
I want to ask another question that related the topic.
One of the important difference between C and C++ is
prefix ++ operator. The operator doesn't yield an l-value
in C but in C++ it yields a l-value.
I tried to overload the prefix ++ oprator for that class;
class MyInt
{
int m_i;
friend ostream & operator<< (ostream &, const MyInt &);
public:
MyInt(int i)
:
m_i(i)
{}
MyInt(const MyInt & r)
{
m_i = r.m_i;
}
MyInt & operator+= (const MyInt & anoth)
{
m_i += anoth.m_i;
return *this;
}
MyInt operator++ (int);
MyInt & MyInt::operator ++()
{
return *this += 1;
}
};
MyInt MyInt::operator++ ( int )
{
MyInt m_r( *this );
++*this;
return m_r;
}
MyInt operator+ (const MyInt & lefts, const MyInt & rights)
{
MyInt result = lefts;
result += rights;
return result;
// Or
// return MyInt( lefts ).operator+= ( rights );
}
int main()
{
MyInt myi( 5 );
// I am expecting error bu doesn't happen. Why?
myi++ = 10;
You're assigning an integer to a temporary. The temporary will
go away as soon as the full expression is evaluated. It will be
destroyed with the value 10. Why would there be an error?
BTW, you stated that you "tried to overload the prefix ++ oprator"
while the class here has the *postfix* operator++ overloaded.
cout << myi;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask