使用++作为通过类成员访问语句的前缀不会导致错误
我现在有点困惑,我正在运行以下代码:
std::vector<int> test{1, 5, 10};
++test.at(1); // I'm trying to increment that number 5 to six, which works
std::cout << test.at(1) << std::endl; // Prints out 6 to the console
我期待它给我一个编译器错误,因为正如我从运算符优先级中读到的,.(用于成员访问)和增量运算符 ( ++) 具有相同的优先级,但它们在语句中从左到右读取,从什么反正我明白了。所以在上面显示的代码中,我认为它等于 say (++test).at(1),这显然会导致编译器错误。为什么即使关联性从左到右也不是这种情况,为什么它会像这样读取它(根据我的想法)...... ++(test.at(1))?如果它们具有相同的优先级,不是吗,就像在数学中一样,例如,使用第++一个然后使用.?
回答
确实,后缀增量 ( a++) 和成员访问 ( .) 具有相同的优先级。
但是您使用的是前缀增量 ( ++a)。
请参阅 cppreference 的优先级图表。
确实,test++.at(i)会因为您给出的原因而出错,尽管作为代码的读者,在这种情况下我们不会以任何方式感到惊讶。
- Nice concise answer. I would like to add: _Never write code in such a manner, so that others have to consult cppreference's operator precedence chart._