/////////////////////////////////////////////////////// // // operators.cpp // // Started 1/16/97 by Jeff Ondich // Last modified: 1/16/97 // // 1. Read the program. What do you think it's going // to do? Don't worry about the details of the // operator overloading syntax. Just try to // get the rough idea of what's going on. // // 2. Note that, strictly speaking, operator> and // operator<< are not member functions of Person. // What about the syntax of the implementations // of operator<< and operator> shows you that they // are not member functions? Why are operator> // and operator<< allowed to use mAge and mName // directly (private data, after all....). // // 3. Try to write and test your own operator== or // operator!= or operator>>. // //////////////////////////////////////////////////////// #include #include /////////////////////////////////////////////////////// // This Person class is ever-so-slightly more // realistic than DopeyClass. Yipee. /////////////////////////////////////////////////////// const int kMaxNameLength = 30; class Person { private: int mAge; char mName[kMaxNameLength]; public: Person( int age, char *name ); private: // Operators. We're going to do // comparison (>) and output (<<). There are many // operators that you can give meanings in this // fashion (==, !=, +, -, *, /, >>, etc.). This is just // a beginning look at operator overloading. friend int operator>( const Person& LHS, const Person& RHS ); friend ostream& operator<<( ostream& out, const Person& RHS ); }; Person::Person( int age, char *name ) { mAge = age; strncpy( mName, name, kMaxNameLength ); } int operator>( const Person& LHS, const Person& RHS ) { if( strcmp(LHS.mName,RHS.mName) > 0 ) return( true ); else return( false ); } ostream& operator<<( ostream& out, const Person& RHS ) { out << RHS.mName << " (age " << RHS.mAge << ")"; return( out ); } /////////////////////////////////////////////////////// // The main program /////////////////////////////////////////////////////// int main( void ) { Person me(36,"Jeff"), her(27,"Zelda"); if( me > her ) cout << me << " is greater than " << her << endl; else cout << her << " is greater than " << me << endl; return( 0 ); }