Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems overloading the << Operator

I am trying to overload the << operator for my Currency class but I get this compiler error: C2143: syntax error : missing ';' before '&'

In my .h file I have:

 friend ostream &operator << (ostream &, const Currency&);

And in my Currency.cpp file I have:

    ostream &operator << (ostream &stream, const Currency &obj){
      stream<<"$"<<obj.dollars<<"."<<obj.cents;
      return stream;
      }

Everything up until now worked fine, but choked once I put that in:

I have the following at the top of my .h file:

    #ifndef CURRENCY_H
    #define CURRENCY_H

  #include<iostream>
  #include<string>
  #include<ostream>
  #include<sstream>

  class Currency; //forward delcaration

  //Function prototypes for overloaded stream operators
  ostream &operator << (ostream &, const Currency &);

I have no idea what I am doing wrong. Help would be great. Thanks

like image 572
Travis Pessetto Avatar asked Jun 21 '26 10:06

Travis Pessetto


1 Answers

ostream is declared in namespace std and you are missing std:: identifier before it:

std::ostream &operator << (std::ostream &, const Currency &);

If you want to avoid std:: then after header file you can put using namespace statement:

...
#include<ostream>
using namespace std;  // this is not desirable though in real world programming

ostream &operator << (ostream &, const Currency &);

Edit: using namespace <> is not recommended in real world programming at the file top. I have put that part just for FYI.

like image 145
iammilind Avatar answered Jun 23 '26 00:06

iammilind