【问题标题】:Why sometimes "." occurs error whlile "->" not? (C++ pointer) [closed]为什么有时“。”发生错误而“->”不是? (C++ 指针)[关闭]
【发布时间】: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-&gt;x(*pv).x 的语法糖。
  • 回答您的问题 - 这是因为运算符优先级。 . 的优先级高于 *,因此您尝试在指针上调用 push_back
  • 顺便说一句,你应该受到赞扬,因为你用一个很好的 MCVE 编写了一个清晰的问题。否决票反映了这是一个常见问题,而不是一个问得不好的问题。

标签: c++ pointers vector operator-precedence


【解决方案1】:

一元运算符* 的优先级低于后缀运算符.

所以这个说法

*pv.push_back(2);

等价于

*( pv.push_back(2) );

你必须改写

( *pv ).push_back(2);

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多