[prog] Overloading operator<<
Sue Stones
suzo at bigpond.net.au
Tue Jun 10 19:00:02 EST 2003
Compiler errors have been added below the repective code.
sue
On Tue, 10 Jun 2003 05:48 pm, Sue Stones wrote:
> 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
g++ Widgit.C -o Widgit
Widgit.C:15: syntax error before `&' token
Widgit.C:39: syntax error before `&' token
make: *** [Widgit] Error 1
[
g++ Widgit.C -o Widgit
Widgit.C:7: ISO C++ forbids declaration of `ostream' with no type
Widgit.C:7: `ostream' is neither function nor member function; cannot be
declared friend
Widgit.C:7: parse error before `&' token
Widgit.C:39: syntax error before `&' token
make: *** [Widgit] Error 1
[
> ------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
>
g++ Widgit.C -o Widgit
Widgit.C:7: ISO C++ forbids declaration of `ostream' with no type
Widgit.C:7: `ostream' is neither function nor member function; cannot be
declared friend
Widgit.C:7: parse error before `&' token
Widgit.C:39: syntax error before `&' token
make: *** [Widgit] Error 1
> _______________________________________________
> Programming mailing list
> Programming at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/programming
More information about the Programming
mailing list