我正在编写一个仅 header 的 matrix3x3 实现,我希望它是独立的并且不依赖于其他 header ,除了我也编写的 vector3 header 。
目前,我希望它重载 ostream << 运算符,但我不想在其中包含 iostream。
如果包含 ostream 是否可以使重载成为可选的并工作,如果不包含它是否可以让所有其余的工作在没有重载的情况下正常工作?
我考虑过检查是否包含 ostream header 的可能性,但它有一个主要缺陷,因为如果 iostream 包含在 matrix3x3 header 之后,它将无法正常工作.
编辑: 我已将 iostream 替换为 ostream,因为我认为它对问题的要点造成了一些混淆。
最佳答案
为什么不使用 <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;
}
请注意,您无法在自己的代码中安全地转发声明标准类。相关问题:
关于c++ - 重载 Iostream C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47462087/