[prog] Overloading operator<<

Sue Stones suzo at bigpond.net.au
Tue Jun 10 17:48:37 EST 2003


I am trying to write an function to define << for the class widgit, but I  
can't get it to compile.  What am I doing wrong.  Below are a couple of the 
options that I have tried, I have copied the class definition and the problem 
function only!

sue

------attempt1-----------

#include <iostream>
#include <strings.h>
using std::cout;
using std::endl;
                                                                                                    
class Widgit {
private:
        int id_num;
        char *description;
public:
        Widgit() {} // default constructor
        Widgit(int id, char * desc ); // init constructor
        Widgit(const Widgit& w); // copy constructor
        Widgit& operator= (const Widgit& w); // define assignment for Wigits
        ostream& operator<< (ostream&, const Widgit&);
					 // define ostream << for Wigits
};//widget
                                                                                                    
ostream& operator<< (ostream& out, const Widgit& w){
        out << w.id_num << ": "
                << w.description << endl;
        return out;
}  // define ostream << for Wigits
  
------attempt 2-----------

#include <iostream>
#include <strings.h>
using std::cout;
using std::endl;
                                                                                                    
class Widgit { 
friend ostream& 
	operator<< (ostream&, const Widgit&); // define ostream << for Wigits
private:
        int id_num;
        char *description;
public:
        Widgit() {} // default constructor
        Widgit(int id, char * desc ); // init constructor
        Widgit(const Widgit& w); // copy constructor
        Widgit& operator= (const Widgit& w); // define assignment for Wigits
       
};//widget
                                                                                                    
ostream& Widgit::operator<< (ostream& out, const Widgit& w){
        out << w.id_num << ": "
                << w.description << endl;
        return out;
}  // define ostream << for Wigits
 


More information about the Programming mailing list