繁体   English   中英

在“cout”语句中调用带有“cout”语句的函数

[英]Called a function with “cout” statement inside a “cout” statement

在搞乱代码时我遇到了这种相当模糊的行为,这是一个例子:

#include <iostream>

using namespace std;


int print(void);

int main(void)
{
    cout << "The Lucky " << print() << endl;     //This line
    return 0;
}

int print(void)
{
    cout << "No : ";
    return 3;
}

在我的代码中,带有注释的声明//This line应该打印出The Lucky No : 3 ,而是打印出No : The Lucky 3 是什么导致这种行为? 这是否与C ++标准有关,或者它的行为因编译器而异?

未指定对函数的参数的评估顺序。 您的行对于编译器看起来像这样:

operator<<(operator<<(operator<<(cout, "The Lucky "), print()), endl);

语句中的主要调用是以endl作为参数的调用。 未指定第二个参数endl是首先计算还是更大的子表达式:

operator<<(operator<<(cout, "The Lucky "), print())

并且打破了那个,没有指定是首先调用函数print()还是子表达式:

operator<<(cout, "The Lucky ")

那么,回答你的问题:

是什么导致这种行为? 这是否与C ++标准有关,或者它的行为因编译器而异?

它可能因编译器而异。

让我们将operator <<称为operator <<简单operator

现在我们可以写了

cout << "The Lucky"

operator(cout, "The Lucky")

这个操作的结果是cout ,它被传递给下一个<< ,所以我们可以写

operator(operator(cout, "The Lucky"), print() )

它是一个带有两个参数的函数调用,标准没有说明它们的评估顺序。

所以对于一些编译器,你真的可以得到

The Lucky No : 3

在我的编译器中No:Lucky 3是输出....这意味着它的行为因编译器而异。

暂无
暂无

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

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