C++ STL字符串运算符+关联性

CXu*_*ong 4 c++ operator-precedence associativity

我在VC++ 2015中尝试了以下代码

#include <iostream>
#include <string>

using namespace std;

int foo(int v)
{
    cout << v << endl;
    return 10;
}

string bar(int v)
{
    cout << v << endl;
    return "10";
}

int main()
{
    auto a = foo(1) + foo(2) + foo(3);
    auto b = bar(10) + bar(20) + bar(30);
    cout << "----" << endl << a << endl << b << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

控制台上的结果如下

1
2
3
30
20
10
----
30
101010
Run Code Online (Sandbox Code Playgroud)

众所周知,二元+运算符具有从左到右的关联性,并且可以通过3次调用来确认foo.它们是通过指令从左到右调用的.

我的问题是,为什么这似乎不适合string::operator+?我是否陷入了一些误解?

Moh*_*ain 8

您在关联性订单或评估之间感到困惑.

在C++中未指定参数的评估顺序.operator +正如你所提到的那样,关联性是从左到右.

要理解这一点,请尝试使用类似的代码段 operator -


订单或评估(强调我的)

除非下面提到,否则在C++中没有从左到右或从右到左评估的概念.这不应与运算符的从左到右和从右到左的关联性混淆:表达式f1()+ f2()+ f3()被解析为(f1()+ f2())+ f3( )由于operator +的从左到右的关联性,但是对f3的函数调用可以在运行时的第一个,最后一个或f1()或f2()之间进行计算.