获取错误"array bound is not an integer constant before ']' token"
Getting error "array bound is not an integer constant before ']' token"
我正在尝试使用数组实现堆栈,但我收到一个错误。
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
,它可以在运行时调整大小。
希望这对你有帮助!
您不能像那样在声明中使用this
。this
是传递给类中的非静态方法的常量指针。
这样的数组声明需要常量值/表达式来表示数组的大小。你不希望那样,你想要一个动态大小的容器。解决方案是使用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);
}
};
相关文章:
- Arduino无法编译名为SP:"Expected ')' before '(' token"的变量
- 为什么我的功能在使用 goto 时会给我带来"expected primary-expression before '}' token"?
- 使用结构和数组时的"expected primary expression before '.' token"
- 如何解决"Expected expression before " = " token"?
- 错误:创建模板类时"expected unqualified-id before '{' token"
- 如何解决"expected constructor, destructor, or type conversion before ‘(’ token"错误?
- 这个编译器错误是什么意思 - "qualified-id in declaration before ‘=’ token" C++?
- 获取链表上的"expected ‘)’ before ‘&’ token"到 BST 构造函数签名
- 使用宏访问指向数据成员的指针会导致"error: expected unqualified-id before ‘*’ token"
- "error: expected primary-expression before '<=' token" 我做错了什么?
- 内存集调用位置的"error: expected constructor, destructor, or type conversion before '(' token"
- 设置if流,获取'error: expected initializer before ‘.’ token'
- 在2D伊辛模型上工作。C++新手。我在第 23 行收到错误"expected unqualified-id before '{' token"
- 我的代码看起来不错。为什么我要得到"error: expected primary-expression before ')' token"?
- 如何修复"Expected Primary-expression before ')' token"错误?
- C++错误"tabulate.cc:19: error: expected primary-expression before ',' token"
- 使用多个文件时"array bound is not an integer constant before ']' token"
- "expected initializer before '<' token"尝试模板成员专用化
- 为什么海湾合作委员会说"a function-definition is not allowed here before '{' token"?
- C++:"error: expected ',' or '...' before '(' token"