【问题标题】:C++ compiler has contradictory complaints about overloading the << operatorC++ 编译器对重载 << 运算符有矛盾的抱怨
【发布时间】:2013-10-08 23:43:23
【问题描述】:

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

它抱怨它必须有两个。我做错了什么?

【问题讨论】:

标签: c++ operator-overloading iostream


【解决方案1】:

运算符的双参数重载必须是非成员函数。要么将其移出类定义,要么将friend 添加到它以使其成为非成员朋友函数,以更有意义的方式为准。

单参数重载没有用,因为它在对象实例是左操作数时使用。

【讨论】:

  • 那么,您会建议将其作为头文件的一部分吗?我不知道有两种方法可以重载函数。我一直在搜索
  • @KG6ZVP:你把定义放在哪里取决于你;只有声明需要在标题中。不过,这是最常见的问题之一,所以我很难相信您找不到任何信息。
  • 问题是没有找到任何信息,而是找到了许多不同的线程,这些线程描述了让 g++ 发疯的事情。我想我现在已经整理好了。在学习重载运算符之前,我停止了自学 C++,而且我对一些基本语法非常生疏。
【解决方案2】:

friend ostream&amp; operator&lt;&lt;(ostream&amp; os, const Date&amp; date);

您还可以在代码中添加一些常量。比如……

bool operator==(const Date&amp; rhs) const;

我还建议您将所有整数设为 int,即使它们只取一个很小的值(例如月份),除非出于技术原因您需要将它们设为字符。

【讨论】:

  • 我只是尽可能地优化存储空间,因为我将创建它的许多实例(数百个或更多)并且它们不会被足够频繁地访问到转换所需的额外时间理解重要。
  • @KG6ZVP 1000 个实例只会为您节省 14kb。
  • @KG6ZVP:那就用int_least8_t,这样你的目的就很明确了。 (年份可以是int_least16_t
  • @Neil:这是 L1/L2 缓存的一大块,即使在 L3 中也很重要。
  • @BenVoigt 过早优化发生了什么?
猜你喜欢
  • 2023-04-09
  • 1970-01-01
  • 2011-01-08
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多