Overloading the << operator error C2804: binary 'operator <<' has too many parameters

19,731

Solution 1

ostream &operator<<(ostream &out, Clock &clockObj); 

should be

friend ostream &operator<<(ostream& out, Clock &clockObj);    

defined OUTSIDE the class.

See here: Should operator<< be implemented as a friend or as a member function?

Solution 2

 ostream &operator<<(ostream &out, Clock &clockObj);

should be

 friend ostream &operator<<(ostream &out, Clock &clockObj);

According to Stanley et al's C++ Primer (Fourth Edition pp 514):

When we define an input or output operator that conforms to the conventions of the iostream library, we must make it a nonmember operator. We cannot make the operator a member of our own class. If we did, then the left-hand operand would have to be an object of our class type

Therefore, it is good practice to overload << and >> as friend functions of the class.

Share:
19,731
varrick
Author by

varrick

Updated on June 04, 2022

Comments

  • varrick
    varrick almost 2 years

    Here is my class:

    #ifndef CLOCK_H
    #define CLOCK_H
    using namespace std;
    
    class Clock
    {
        //Member Variables
    
        private: int hours, minutes;
    
        void fixTime( );
    
        public:
            //Getter & settor methods.
            void setHours(int hrs); 
            int getHours() const;
            void setMinutes(int mins); 
            int getMinutes() const; 
    
            //Constructors
            Clock(); 
            Clock(int);
            Clock(int, int);
            //Copy Constructor
            Clock(const Clock &obj);
            //Overloaded operator functions
            void operator+(const Clock &hours);
            void operator+(int mins);
            void operator-(const Clock &hours);
            void operator-(int minutes1);
            ostream &operator<<(ostream &out, Clock &clockObj); //This however is my problem where i get the error C2804. Saying that it has to many parameters 
    };
    #endif
    

    All this function is supposed to do is out the values of a clock at different times.

    • chris
      chris about 11 years
      It has three parameters. It should have two.
    • paddy
      paddy about 11 years
      For future reference, please don't use the code-highlighting backticks when you post a code block. There is a separate button for that (or you simply indent each line with 4 spaces.
  • varrick
    varrick about 11 years
    Wow.. Thank you so much. I probably look really stupid. Thank you again.
  • Mooing Duck
    Mooing Duck about 11 years
    Mostly right, but it doesn't have to be defined outside of the class.