cout语句中的c ++函数调用 [英] c++ function call within cout statement

查看:67
本文介绍了cout语句中的c ++函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++,最近遇到一个令人困惑的问题,这是代码:

I'm learning c++, and recently run into a confusing problem, here's the code:

#include <iostream>

using namespace std;

class A {
    public:
        A() { a[0] = 1; a[1] = 0; }
        int a[2];
        int b(void) { int x=a[0];a[0]=a[1];a[1]=x; return x; }
};

int main(void) {
    A a;
    cout<<a.a[0]<<a.a[1]<<endl; //outputs 10
    a.b();
    cout<<a.a[0]<<a.a[1]<<endl; //outputs 01
    a.b();
    cout<<a.a[0]<<a.a[1]<<endl; //outputs 10

    cout << a.b() << //outputs 1
    endl<< a.a[0]<<a.a[1] << endl; //outputs 10???

    cout<<a.a[0]<<a.a[1]<<endl; //outputs 01???
    return 0;
}

b()的前两个调用的行为符合预期,但是当我在cout语句中调用b()时,它不会立即切换数组的两个元素,但是后来我检查了一下,它已经切换了.

The first two calls of b() behaves as expected, but when i call b() within the cout statement, it doesn't switch the two elements of the array right away, but later i check it, it's already switched.

您能帮助我了解这种行为吗?谢谢.

Can you help me understand this behavior? Thank you.

推荐答案

std :: cout<<f()<<g();

两个函数调用的求值顺序不确定.编译器可以先调用 g()然后调用 f(),或者先调用 f()然后调用 g().

The order of evaluation of the two function calls is unspecified; the compiler can call g() then f(), or it can call f() then g().

代码中的内容相同;编译器可以松开 aa [0] 的值调用 ab(),也可以调用 ab()然后获取值的 aa [0] .

Same thing in your code; the compiler can squirrel away the value of a.a[0] the call a.b(), or it can call a.b() then grab the value of a.a[0].

这篇关于cout语句中的c ++函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆