c++ - 数组下标的无效类型 `int[int]'

标签 c++ arrays templates subscript

我正在尝试编译下一段代码,但在指示的行上出现此错误

“数组下标的无效类型‘int[int]’”

代码:

template<typename T>
class Stack {
      private:
              static const int GROW_FACTOR = 2;
              static const int START_LENGHT = 10;

              T * data;
              int max;
              int used;

              void allocateIfNeeded() {
                   if (used == max) {
                      T * aux = new T[max*GROW_FACTOR];
                      for (int i=0; i<max; i++) {
                          aux[i] = data[i];
                      }
                      max *= GROW_FACTOR;
                      delete[] data;
                      data = aux;
                   }
              }
      public:
             Stack() {    
                 max = START_LENGHT;
                 data = new T[max];
                 used = 0;
             }

             void push(T data) {
                 allocateIfNeeded();
                 data[used++] = data; // <-- compile error
             }

             T pop() {
                 return data[--used];
             }

             T top() {
                 return data[used-1];
             }

             bool isEmpty() {
                  return used == 0;
             }           
};

当出现此错误消息时,我已经检查了其他情况,但我认为它们与此无关。

最佳答案

参数名data隐藏了对象成员名data在函数范围内。要引用它,您必须使用 this->data 明确限定它:

        void push(T data) {
             allocateIfNeeded();
             this->data[used++] = data; // <-- compile error
         }

或者使用某种标识符命名方案(例如在成员前加上“m_”前缀),这会导致名称参数与成员的名称不同。

关于c++ - 数组下标的无效类型 `int[int]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11063367/

相关文章:

c++ - GetThreadContext 寄存器总是返回 0xCCCCCCCC

c++ - 将输入存储到数组 C++

c++ - 字符串数组长度 C++ 问题?

javascript - 根据 javascript 中的数字/对象对数组或 json 进行排序

c++ - 尝试为所有 std 容器打印重载运算符 << 时出错,为什么?

c++ - 在继承层次结构中将接口(interface)与实现分离(C++ 新手)

C、多维数组: array whose elements are one-dimensional arrays?

Java 搜索数组中存在的元素

c++ - 为什么在涉及模板类时派生类无法访问基函数

c++ - 模板函数在读取时返回错误值