运算符

问题描述 投票:11回答:3

我很难理解下面代码中的调用顺序。我期望看到下面的输出

    A1B2

虽然我可以看到我得到的输出是

    BA12

我认为通话std::cout<< b->fooA() << b->fooB() << std::endl等同于通话

  std::cout.operator<<( b->fooA() ).operator<< ( b->fooB() )

但我可以看到情况并非如此。您能否帮助我更好地了解其工作原理以及与全局operator<<的关系?这是此顺序中最后一次调用过吗?

#include <iostream>

struct cbase{
    int fooA(){
        std::cout<<"A";
        return 1;
    }
    int fooB(){
        std::cout <<"B";
        return 2;
    }
};

void printcbase(cbase* b ){
    std::cout << b->fooA() << b->fooB() << std::endl;
}

int main(){
    cbase b;
    printcbase( &b );
}

我很难理解下面代码中的调用顺序。我期待看到A1B2以下的输出,虽然我看到的输出是BA12,但我认为...

c++ stream operator-keyword cout ostream
3个回答
10
投票

编译器可以这样评估函数printcbase()


6
投票

<<的执行顺序已明确定义,但在C ++中未定义子表达式的求值顺序。 This article and the C code example说明了您提到的问题。


3
投票

移位运算符是左联想的; a << b << c读取为(a << b) << c,这意味着如果a是具有用户定义的成员operator<<的类型(并返回该类型),则表达式将读取为a.operator<<(b).operator<<(c)。如果改为使用免费的operator<<,则其读为operator<<(operator<<(a, b), c)

© www.soinside.com 2019 - 2024. All rights reserved.