// CS19 Fall 2005 Code example // demonstration of Operator Overloading // This is a modified version of displays 8.6 and 8.7 from // Absolute C++, 2nd edition, Walter Savitch, Addison Wesley #include #include using namespace std; class intPair{ public: intPair(int f, int s){ first = f; second = s;} void setFirst(int n){ first = n;} void setSecond(int n){ second = n;} int getFirst( ) const{ return first;} int getSecond( ) const{ return second;} intPair operator++( ); //Prefix version intPair operator++(int); //Postfix version int& operator[](int index); private: int first; int second; }; // overload the post-increment operator // int ignorMe is a marker only -- don't use it intPair intPair::operator++(int ignoreMe){ int fnum = first; int snum = second; first++; second++; return intPair(fnum, snum); } // overload the pre-increment operator intPair intPair::operator++( ){ first++; second++; return intPair(first, second); } //requires use of iostream and cstdlib: int& intPair::operator[](int index){ if (index == 1) return first; if (index == 2) return second; cerr << "Illegal index value in call to intPair::operator[]." << endl; exit(1); } // ------------------------------------------------------------ int main( ){ intPair a(1,2); cout << "Postfix a++: Start value of object a: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; intPair b = a++; cout << "Value returned: "; cout << b.getFirst( ) << " " << b.getSecond( ) << endl; cout << "Changed object: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; // simple object so default memberwise copy works fine a = intPair(1, 2); cout << "Prefix ++a: Start value of object a: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; intPair c = ++a; cout << "Value returned: "; cout << c.getFirst( ) << " " << c.getSecond( ) << endl; cout << "Changed object: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; a = intPair(1,2); cout << "Start value of object a: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; cout << "operations: a[1] = 5; a[2] = 7;" << endl; a[1] = 5; a[2] = 7; cout << "End value of object a: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; }