顺便说一句,我在 arch linux 上使用 eclipse 和 g++(不到一周前我运行了 pacman -Syu,所以一切都是最新的)。
每次我尝试编译时,Eclipse 都会产生一个错误:
#ifndef DATE_HPP_
#define DATE_HPP_
using namespace std;
class Date {
public:
int Year;
char Month;
char Day;
char HH;
char MM;
char ss;
Date();
/*
* Overloaded Operator Functions
*/
//Assignments
Date operator=(Date input);
//Comparisons
bool operator==(Date& rhs);
bool operator!=(Date& rhs);
bool operator<(Date& rhs);
bool operator>(Date& rhs);
bool operator<=(Date& rhs);
bool operator>=(Date& rhs);
//Conversion
operator char*();
operator std::string();
ostream& operator<<(ostream& os, const Date& date); //TROUBLE LINE
};
#endif /* DATE_HPP_ */
Eclipse 在 operator<< 声明中显示一条消息,说明它必须只有一个参数。然而,当我这样声明时:
ostream& operator<<(const Date& date);
它提示它必须有两个。我做错了什么?
最佳答案
运算符的双参数重载必须是非成员函数。要么将其移出类定义,要么向其添加 friend
使其成为非成员友元函数,以更有意义的为准。
单参数重载没有用,因为当对象实例是左操作数时使用它。
关于C++ 编译器对重载 << 运算符有矛盾的提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19260480/