c++ - 重载ostream运算符c++时出错

标签 c++ operator-overloading

我正在重载我的类的 ostream/istream 运算符函数友元函数,但它给出了错误: ostream 没有命名类型。 没有或有头文件#include<iostream>它给出了错误

date.h:24:9: error: ‘ostream’ does not name a type friend ostream& operator<< (ostream &out, Date &today);

最佳答案

名称ostream 位于std 命名空间中,因此您需要引入该名称。侵入性最小的方法是明确限定它:

friend std::ostream& operator<< ....
       ^^^

另一种方法是使用using-或using namespace-指令。它们允许您将名称导入翻译单元的其余部分:

using std::ostream; // cherry-pick the names
friend ostream& operator<< ....

using namespace std; // fire a shotgun with a huge and growing bunch of names
friend ostream& operator<< ....

这些都有优点和缺点:

  • 名称变得更短,在上下文中可能更易读
  • 当其他命名空间定义相同的名称时,可能会出现名称冲突(考虑例如 std::powawesome_math_lib::pow)。

好的 C++ 代码的公认经验法则是永远不要在头文件的全局命名空间中使用 usingusing namespace,并且要小心在源文件中。

许多人还同意 std:: 是如此简短和标准,以至于他们从不在其上使用 usingusing namespace(除了在函数)并坚持输入 std::...

关于c++ - 重载ostream运算符c++时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488341/

相关文章:

interface - 在类型定义之外实现相等

ruby - 在 Ruby 中,我可以覆盖三元运算符 '?'

c++ - 如何实现实例前可用的运算符(前置)

Python——使用现有类方法的特殊方法算术

c++从资源中加载图像visual studios 2012在窗口上绘制

c++ - 类模板中的多个可选成员,无需开销

c++ - Qt 选择现有文件

c++ - 与正零 (+0.0) 相比,负零 (-0.0) 的行为

C++ 运算符 () 和 'using' 声明 : Left operand must be l-value error

c++ - 如何使用 C++ 在启动时打开一个新窗口?