Overloading the << operator error C2804: bin

2019-01-26 16:19发布

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.

2条回答
狗以群分
2楼-- · 2019-01-26 16:47
 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.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-26 17:05
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?

查看更多
登录 后发表回答