cout <<如何实际工作?

Ori*_*Ori 46 c++ cout

我想知道如何std::cout使用<<它.

我的主要困惑在于是否std::cout作为某种事物的实例.基本上,如何<<定义?如果我为自定义类执行此操作,我需要某种类型的实例...

我可以看到它实现它是一种带有无效指针的东西,但我希望看到它的实际方式.

这里有人知道吗?谢谢

Bil*_*eal 48

std::cout是一个实例std::ostream.std::cout << "something"调用其中一个operator<<重载,就像对任何实例一样std::ostream.

它是"特殊的",因为它引用了控制台,但是它的行为完全像一个ofstream或一个ostringstream.

编辑:链接工作就像它适用于任何其他运营商.考虑:

class MyType
{
    friend std::ostream& operator<<(std::ostream& target, const MyType& source);
    int val;
public:
    MyType()
        : val(0)
    { }
    MyType& Add(int toAdd)
    {
        val += toAdd;
        return *this;
    }
};

MyType& operator+(MyType& target, int toAdd)
{
    return target.Add(toAdd);
}

std::ostream& operator<<(std::ostream& target, const MyType& source)
{
    target << source.val;
    return target; //Make chaining work
}

int main()
{
    MyType value1;
    value1 + 2 + 3 + 4;
    std::cout << value1 << " and done!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,链接+ s MyType工作的原因与<<s工作相同std::ostream.这两个+<<是左结合的,这意味着从左至右他们正在评估.对于重载运算符,运算符将替换为等效函数调用.

编辑2:更详细一点:

假设您是编译器并且正在解析

std::cout << value1 << " and done!" << std::endl;
Run Code Online (Sandbox Code Playgroud)

首先,<<左边是关联的,所以你从左边开始.您评估第一个<<并将其转换为函数调用:

operator<<(std::cout, value1) << " and done!" << std::endl;
Run Code Online (Sandbox Code Playgroud)

然后你会看到你再次拥有std::ostream(调用的结果operator<<)和a char *,你又一次变成了函数调用:

operator<<(operator<<(std::cout, value1)," and done!") << std::endl;
Run Code Online (Sandbox Code Playgroud)

等等,直到你处理完整个陈述.

  • @pst:所有`operator <<重载的形式都是`std :: ostream&operator <<(std :: ostream&target,TYPE&source)`,它们返回作为源传入的引用.也就是说,`std :: cout << a << b;`与`operator <<相同(operator <<(std :: cout,a),b);` (5认同)
  • +1 但是(作为倡导者),链接是如何工作的?(例如`std::cout &lt;&lt; a &lt;&lt; b ...`) (2认同)
  • `cout` 不引用控制台,它引用操作系统的默认输出。在某些操作系统中,这恰好是一个控制台。 (2认同)