在操作符中的执行顺序< [英] order of execution in operator<<
问题描述
我在下面的代码中理解调用顺序有困难。
我期待看到下面的输出
A1B2
pre>
虽然我可以看到我得到的输出是
BA12
我以为呼叫
std :: cout< b - > fooA()<< b - > fooB()<< std :: endl
等同于调用std :: cout.operator<< - > fooA()).operator<< (b-> fooB())
但我可以看到情况并非如此。你能帮助我更好地理解它是如何工作的,以及与全局
运算符<<
的关系?
注意
AFAG
#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);
}
解决方案编译器可以
printcbase()
如下:void printcbase(cbase * b) {
int a = b-> FooA(); // line 1
int b = b-> FooB(); // line 2
std :: cout<<一个; // line 3
std :: cout<< b; // line 4
stc :: cout<< std :: endl;
}
或许多标记为1 - 4的行中的一些保证线1在线3之前完成,线2在线4之前(当然线3之前在线4之前)。标准不说更多,确实可以预期不同的C ++编译器的不同结果。
I have difficulties in understanding the sequence of calls in the code below. I was expecting to see the output below
A1B2
While I can see that the output I get is
BA12
I thought that the call
std::cout<< b->fooA() << b->fooB() << std::endl
was equivalent to callstd::cout.operator<<( b->fooA() ).operator<< ( b->fooB() )
but I can see that this is not the case. Can you help me understanding better how this does it work and the relationship with the global
operator<<
? Is this last ever called in this sequence?Regards
AFAG
#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 ); }
解决方案The compiler can evaluate the function
printcbase()
as this:void printcbase(cbase* b ){ int a = b->FooA(); // line 1 int b = b->FooB(); // line 2 std::cout << a; // line 3 std::cout << b; // line 4 stc::cout << std::endl; }
or some of many permutatins of lines marked as 1 - 4. You are only guaranteed that that the line 1 is done before the line 3, and line 2 before the line 4 (and of course line 3 before line 4). Standard does not say more and indeed you can expect different results with different C++ compilers.
这篇关于在操作符中的执行顺序<的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!