这是我的类:
#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
所有这些函数应该做的就是在不同的时间输出时钟的值。
ostream &operator<<(ostream &out, Clock &clockObj);
应该是
friend ostream &operator<<(ostream& out, Clock &clockObj);
在类外部定义。
请参见此处:是否应该使用运算符<lt;是作为朋友实现还是作为成员功能实现?
ostream &operator<<(ostream &out, Clock &clockObj);
应该是
friend ostream &operator<<(ostream &out, Clock &clockObj);
根据Stanley等人的C++Primer(第四版,第514页(:
当我们定义符合iostream库的约定,我们必须使其成为非成员操作人员我们不能使运算符成为我们自己类的成员。如果我们完成,则左侧操作数必须是类
因此,将<<
和>>
作为类的友元函数重载是一种很好的做法。