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

car*_*995 15 c++ cout function

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*ley 18

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

operator<<(operator<<(operator<<(cout, "The Lucky "), print()), endl);
Run Code Online (Sandbox Code Playgroud)

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

operator<<(operator<<(cout, "The Lucky "), print())
Run Code Online (Sandbox Code Playgroud)

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

operator<<(cout, "The Lucky ")
Run Code Online (Sandbox Code Playgroud)

那么,回答你的问题:

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

它可能因编译器而异.