【问题标题】:sending std::endl to stream gives memory address发送 std::endl 到流给出内存地址
【发布时间】:2015-09-21 21:29:10
【问题描述】:

有人能解释一下为什么这个程序会向 std::cout 发送地址吗?

#include<string>
#include<iostream>
#include<fstream>


std::ostream& stuff(std::ostream& o, std::string s)
{
    o << s << std::endl;
    return o;
}

int main(){

    std::cout << stuff(std::cout, "word") << std::endl;

}

这是由 main() 中的 std::endl 引起的。但是为什么呢??

输出:

word
0x804a064

【问题讨论】:

    标签: c++ stream endl


    【解决方案1】:

    您的函数stuff 返回传递给它的std::ostream

    这意味着你的代码:

    std::cout << stuff(std::cout, "word") << std::endl;
    

    实际会调用:

    std::cout << (std::cout) << std::endl;
                 ^^^^^^^^^^^ this is the result of calling "stuff"
    

    您正在输出std::cout 对象的地址。

    您的程序在功能上等同于:

    std::cout << "word" << std::endl;
    std::cout << std::cout << std::endl;
    

    【讨论】:

    • 为什么在 main() 中删除 endl 时输出会发生变化?该地址将消失。
    • @lotolmencre 在您的问题中的任何地方都没有描述。如果您有新问题,请提出新问题。祝你好运!
    • @lotolmencre 仅供参考,使用 gcc 4.9.2 编译会在 main 函数中使用和不使用 std::endl 打印地址。
    • @lotolmencre 试试std::cout &lt;&lt; std::cout &lt;&lt; std::endl;,你应该会看到你得到了相同的确切地址。为什么从 main 函数中删除 std::endl 会改变行为是另一个问题。
    • nvm,我想我明白了。 operator
    猜你喜欢
    • 2011-01-20
    • 2015-09-17
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多