重载 Iostream C++

Overloading Iostream C++

我正在写一个 header 只有 matrix3x3 的实现,我想独立并且不依赖其他 headers 除了我也写的 vector3 header。

目前,我希望它重载 ostream << 运算符,但我不想在其中包含 iostream

如果包含 ostream 是否可以使重载可选并工作,如果不包含它是否可以让所有其余工作在没有重载的情况下正常工作?

我考虑过检查是否包含 ostream header 的可能性,但它有一个重大缺陷,因为如果 它将无法正常工作iostream 包含在 matrix3x3 header 之后。

编辑: 我已经用 ostream 替换了 iostream 因为我认为它对问题的要点造成了一些混乱。

为什么不使用 <iosfwd>

示例:

#include <iosfwd>

class Example
{
public:
    Example(int i) : i(i) {}
private:
    int i;
    friend std::ostream& operator<<(std::ostream& os, Example const& example);
};

#include <iostream>

int main()
{
    Example e(123);
    std::cout << e << '\n';
}

std::ostream& operator<<(std::ostream& os, Example const& example)
{
    os << example.i;
    return os;
}

请注意,您不能在您自己的代码中安全地转发声明标准类。相关问题:

  • Forward declare an STL container?
  • Forward Declaration of variables/classes in std namespace