gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:49 26 4
gpt4 key购买 nike

我正在重载我的类的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com