I have a program following:
class INT {
public:
INT(int ii = 0) : i(ii) {}
operator int() { return i; }
private:
int i;
};
int main()
{
INT i;
cin >> i;
}
the statement cin >> i is compiled error, but I don’t know the reason?
In my option, the compiler can find the function cin.operator>>(int&) for that statement, since INT can be converted to int through INT::operator int().
You
operator int()returns a temporary, which can’t bind to a reference-to-non-const that theoperator>>expects (since it needs to change that variable).Change that to
operator int&()and add aconstoverload asoperator int const&() const.