// cout_friend.cpp define the cout operator << for a class // define operator < for a class // demonstrate constructor initialization :var(arg) // a_class.h should be in a file by itself #include // basic console input/output using namespace std; // bring standard include files in scope class A_class { public: A_class(int Akey, double Aval): key(Akey), val(Aval) {} friend ostream &operator << (ostream &stream, A_class x); bool operator < (A_class &y) {return this->key < y.key;} private: // bug in VC++ means this has to be public in VC++ only int key; double val; }; // #include "a_class.h" // would be needed if lines above were in a_class.h int main() { A_class a(5,7.5); A_class b(6,2.4); cout << "a= " << a << " b= " << b << endl; // using A_class << if( a < b) // using A_class < { cout << "OK a < b because 5 < 6" << endl; } else { cout << "BAD compare on a < b fix operator < definition" << endl; } return 0; } // end main // The lines below should be in a file a_class.cpp .cc .C // #include "a_class.h" // The 'friend' statement in A_class makes key and val visible here ostream &operator<< (ostream &stream, A_class x) { stream << x.key << " "; stream << " $" << x.val << " "; // just demonstrating added output return stream; } // output of execution is: // a= 5 $7.5 b= 6 $2.4 // OK a < b because 5 < 6