简体   繁体   English

重载Iostream C ++

[英]Overloading Iostream C++

I'm writing a header only matrix3x3 implementation which I want to be independent and not relying on other headers except for a vector3 header which i also wrote. 我正在编写仅矩阵标头的matrix3x3实现,我想要独立并且不依赖其他标头,但我也写了vector3标头。

Currently, I want it to overload ostream << operator but I don't want to include the iostream in it. 当前,我希望它重载ostream <<运算符,但我不想在其中包含iostream

Is it possible to make the overloading optional and work if ostream is included, and if its not included to have all the rest work fine just without the overload? 如果包括了ostream ,是否可以使重载为可选并且可以工作,并且如果不包括ostream ,则可以使所有其余部分在没有重载的情况下都能正常工作?

I thought about the possibility of checking if the ostream header is included but it has a major flaw because it would not work correctly if iostream was included after the matrix3x3 header. 我考虑过检查是否包含ostream标头的可能性,但是它有一个主要缺陷,因为如果在Matrix3x3标头之后包含iostream ,它将无法正常工作。

Edit: I've replaced iostream with ostream as i think it created a bit of confusion regarding the point of the question. 编辑:我已经更换了的iostreamostream的 ,因为我觉得它创造了关于这个问题的点了一些混乱。

Why not use <iosfwd> ? 为什么不使用<iosfwd>

Example: 例:

#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;
}

Note that you cannot safely forward-declare standard classes in your own code. 请注意,您不能在自己的代码中安全地转发声明标准类。 Related questions: 相关问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM