C++ 编译器对重载 << 运算符有矛盾的提示

标签 c++ operator-overloading iostream

顺便说一句,我在 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/

相关文章:

c++ - Eigen 多线程操作

c++ - g++ std::set 找不到为类定义的运算符<

c++ - 模板和字符串转换

c++ - 实现与 <<? 一起使用的有界字符串格式化运算符的有效方法

c++ - printf 导致崩溃

c++ - 斐波那契和 'if constexpr'

java - 实现持久 B 树

加号运算符的 C++ 重载

c++ - 使用类特定的 set_new_handler

不能使用 MS Visual C++ 在 C 中包含 iostream?