错误:']'令牌之前的预期主表达式 (C++)

Error: Expected Primary-Expression Before ']' Token (C++)

本文关键字:表达式 C++ 令牌 错误      更新时间:2023-10-16

我遇到了一个不断出现的错误。这是一个家庭作业,其中很大一部分包含在一个单独的.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操作总体上是错误的,因为退出函数后数组将被销毁,指针将无效。