获取错误"array bound is not an integer constant before ']' token"

Getting error "array bound is not an integer constant before ']' token"

本文关键字:before token constant an array 取错误 bound is 获取 not integer      更新时间:2023-10-16

我正在尝试使用数组实现堆栈,但我收到一个错误。

class Stack{
private:
    int cap;
    int elements[this->cap]; // <--- Errors here
    int top;
public:
  Stack(){
     this->cap=5;
     this->top=-1;
};

指示行有以下错误:

Multiple markers at this line
- invalid use of 'this' at top level
- array bound is not an integer constant before ']' token

我做错了什么?

在c++中,数组的大小必须是编译时已知的常量。如果不是这样,您将得到一个错误。

这里是

int elements[this->cap];

注意,this->cap不是编译时已知的常量,因为它取决于cap的大小。

如果你想有一个可变大小的数组,它的大小是以后确定的,考虑使用std::vector,它可以在运行时调整大小。

希望这对你有帮助!

您不能像那样在声明中使用thisthis是传递给类中的非静态方法的常量指针。

这样的数组声明需要常量值/表达式来表示数组的大小。你不希望那样,你想要一个动态大小的容器。解决方案是使用std::vector .

既然其他人已经解释了这个问题的原因,这里是一个可能的解决方案。由于在编译时似乎不知道数组的大小,并且赋值可能会限制std::vector<int>的使用,因此考虑使用指针实现。

#include <algorithm>
class Stack{
private:
    int cap;
    int* elements; // use a pointer
    int top;
public:
    Stack(){
        this->cap=5;
        this->top=-1;
        elements = new int[this->cap];
    }
    Stack(const Stack& s) 
         : cap(s.cap) , top(s.top), elements(NULL)
    {
         if(cap > 0) {
             elements = new int[cap];
         }
         std::copy(s.elements , s.elements + cap, elements );
    }
    Stack& operator=(Stack s) {
         swap(s, *this);
         return  *this;
    }
    ~Stack() {delete [] elements;}
    friend void swap(Stack& first, Stack& second)
    {
        using std::swap; 
        swap(first.top, second.top);
        swap(first.cap, second.cap);
        swap(first.elements, second.elements);
    }
};
相关文章: