20071116

C++: Example of class with ctor, increment operator (prefix and suffix) and ostream overloading.

// simple Int class with ctor, increment operator and ostream overload 
class Int{
public:
Int& operator++();
const Int operator++( int n );

Int(int i): _i(i) { };

friend ostream& operator <<(ostream& os, const Int &i);
private:
int _i;
};

// look difference between return values: Int& (in prefix)
Int& Int::operator++() {
_i++; // Handle case where no argument is passed.
return *this;
}

// and const Int (in postfix)
const Int Int::operator++( int n ) {
Int tmp(*this);

if( n != 0 )
for (int nr=0; nr<n; ++nr, ++(*this));
else
++(*this);

return tmp;
}

// overloading << operator for Int class
ostream& operator <<(ostream& os, const Int &i) {
os << i._i;
return os;
}

void main() {

Int gg(0);
cout << gg.operator++(25) << endl ; // Increment by 25 but shown 0
cout << gg << endl; // in next reference is shown as 25

// gg = 25
cout << gg++ << endl; // gg is 25. Only in the next reference will it be 26
cout << gg << endl; // gg is 26.
// gg = 26
cout << ++gg << endl; // ggia is immidiately 27
cout << gg << endl; // ggia is 27

return;
}
Link: Περισσότερα για την διαφορά prefix/suffix.

Δεν υπάρχουν σχόλια:

eggs.in.art (my non-technical blog)