错误:']'令牌之前的预期主表达式 (C++)
Error: Expected Primary-Expression Before ']' Token (C++)
我遇到了一个不断出现的错误。这是一个家庭作业,其中很大一部分包含在一个单独的.h文件中,所以我不会发布所有的代码来保持内容的完整性。以下是相关部分:
//在.h:中
class array_list
{
private:
unsigned int * m_storage;
// points to current position in the list
// in documentation # marks the current position in the list
// ie. if l={#1,2,3} the 1 is the current position in the list
// if l={1,2,#3} the 3 is the current position in the list
// the # is ONLY for documentation purposes
unsigned int m_current;
unsigned int m_size;
unsigned int m_capacity;
//等
//指南:
// Construct a new, empty list.
//
// Pre-conditions:
// none
// Post-conditions:
// m_storage is initialized to point to an array of size INIT_SIZE
// m_capacity is initialized to INIT_SIZE
// m_current is set to -1
// m_size is set to 0
//我写的:
array_list::array_list()
{
int arrayOf[INIT_SIZE];
m_storage = arrayOf[]; /* <---THE PROBLEM LINE */
m_capacity = INIT_SIZE;
m_current = -1;
m_size = 0;
}
由于某种原因,我得到了一个错误,即编译器在所示行的']'标记之前需要一个主表达式。我已经浏览了我的笔记,并在谷歌上进行了一些搜索,看起来这确实是声明数组并用预定义指针指向它的方法,不是吗?有人能帮我解决这个问题吗?非常感谢。
m_storage = arrayOf[];
是无效语法。
m_storage = arrayOf;
将沿着正确的轨道开始(int []
衰减为int*
),但仍然存在问题,因为m_storage
被定义为:
unsigned int * m_storage;
因此CCD_ 4指向的任何数据都应该是CCD_
m_storage = reinterpret_cast<unsigned int *>( arrayOf );
或者(更好的解决方案)您将阵列定义为unsigned int
:的阵列
unsigned int arrayOf[INIT_SIZE];
当然,这里仍然存在问题
这是因为您在(函数的)堆栈上创建数组,然后让它超出范围,从而使指针无效
还有两种方法可以解决这个问题:
初始化对象中的缓冲区:
在头文件(类定义)中:
class array_list
{
private:
unsigned int m_storage[INIT_SIZE];
unsigned int m_current = -1;
unsigned int m_size = 0;
unsigned int m_capacity = INIT_SIZE;
//...
}
这将设置构造array_list
时的默认值。
另一种选择可能更接近您的意图(我不能100%确定),并涉及到在堆栈上分配内存:
array_list::array_list()
{
m_storage = new unsigned int[INIT_SIZE];
m_capacity = INIT_SIZE;
m_current = -1;
m_size = 0;
}
请记住,您现在需要为类编写析构函数,使用delete[]
来取消定位new
的内存:
array_list::~array_list()
{
delete[] m_storage;
}
如果你这样做了,你应该全程执行三(或五)条规则。
重写此语句
m_storage = arrayOf[];
作为
m_storage = reinterpret_cast<unsigned int *>( arrayOf );
虽然看起来很奇怪,m_storage
的类型是unsigned int *
,而您正试图将int *
类型的对象分配给它
正如hvd所指出的,您正在将本地数组的地址分配给数据成员m_storage。因此,fun操作总体上是错误的,因为退出函数后数组将被销毁,指针将无效。
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 提升精神:解析布尔表达式并简化为规范范式
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用正则表达式regex_search在字符串中查找字符串
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 概念中的cv限定符需要表达式参数列表
- 为什么constexpr的性能比正常表达式差
- 对于结构,表达式必须是可修改的ivalue
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 将fold表达式与std::一起用于两个元组
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 标记 '","' 之前的预期主表达式
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 带有用户定义类的c++折叠表达式
- 即使使用调试编译标志,表达式也是"optimized out"
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 这 4 个 lambda 表达式之间有什么区别?