这是我的班级:
#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
所有这个功能应该是在不同时间超出时钟的值。
答案 0 :(得分:15)
ostream &operator<<(ostream &out, Clock &clockObj);
应该是
friend ostream &operator<<(ostream& out, Clock &clockObj);
在课堂外定义。
见这里:Should operator<< be implemented as a friend or as a member function?
答案 1 :(得分:10)
ostream &operator<<(ostream &out, Clock &clockObj);
应该是
friend ostream &operator<<(ostream &out, Clock &clockObj);
根据Stanley等人的C ++ Primer(第四版第514页):
当我们定义符合的输入或输出运算符时 iostream库的约定,我们必须使它成为非成员 运营商。我们不能让运算符成为我们自己的类的成员。要是我们 那么,左手操作数必须是我们的对象 班级类型
因此,最好将<<
和>>
重载为该类的朋友函数。