【发布时间】:2021-12-31 09:00:59
【问题描述】:
感谢您的关注! 使用“.”时出错以下是我的代码。
using namespace std;
#include <vector>
#include <iostream>
void main() {
vector<int> v;
vector<int>* pv = &v;
v.push_back(1);
pv->push_back(2);
//*pv.push_back(2); //error1
for (auto it = v.begin(); it != v.end(); it++) { cout << *it << endl; }
for (auto it = pv->begin(); it != pv->end(); it++) { cout << *it << endl; }
//for (auto it = *pv.begin(); it != *pv.end(); it++) { cout << *it << endl; } //error2
cout << typeid(pv->begin()).name() << endl;
//cout << typeid(*pv.begin()).name() << endl; //error3
}
【问题讨论】:
-
pv->x是(*pv).x的语法糖。 -
回答您的问题 - 这是因为运算符优先级。
.的优先级高于*,因此您尝试在指针上调用push_back。 -
顺便说一句,你应该受到赞扬,因为你用一个很好的 MCVE 编写了一个清晰的问题。否决票反映了这是一个常见问题,而不是一个问得不好的问题。
标签: c++ pointers vector operator-precedence