vineoff said:
Okay.
Next question.
struct C
{
operator int*() { int a = 54; return &a; }
};
int main()
{
C a;
std::cout<<a[0]<<a[0];
}
Why does that print 54 at the first time?
Generally it's a better idea not to write conversion methods (since
their behavior can be surprising as the above program shows). Instead,
I would overload particular operators where doing so make sense.
In this case, overloading the [] (subscript) operator lets the program
return a result by value. And values are less like to cause problems
than pointers (at least of the kind that the program above
demonstrates):
#include <iostream>
struct C
{
int operator[](int) const { return 54; }
};
int main()
{
C a;
std::cout << a[0] << a[0];
}
Greg