为什么我不能用" - >"和"this"和"[]"?

Chr*_*oks 1 c++ oop pointers

我正在玩组合,在我的一个类中,我有一个包含下标运算符"[]"(来自std :: vector)的包装器.但是,当我说时,编译器(g ++)会生气this->[i].我通过使用(*this)[i]而解决了这个问题,但我认为这些是同义词.我错过了什么?这是一个抛出错误的小示例代码(我故意避免使用迭代器newmethod来简单地说明我的问题).

#include <vector>
#include <iostream>

class A {
  private:
    std::vector<int> rep;
  public:
    std::size_t size() { return rep.size(); }
    int& operator[](std::size_t index) { return rep[index]; }
    void newmethod();

    A(size_t n, int m) : rep(n,m) {}
};

void A::newmethod() {
  for (std::size_t i=0; i < (this->size()); ++i) {
    std::cout << (*this)[i] << " ";
  }
  for (std::size_t i=0; i < (this->size()); ++i) {
    std::cout << this->[i]; << " "; //Causes an error!
  }
  return;
}

int main() {
  A(17,3).newmethod();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ans 7

你必须operator[]直接调用成员函数,例如:

this->operator[](i)
Run Code Online (Sandbox Code Playgroud)