【问题标题】:Error: Expected Primary-Expression Before ']' Token (C++)错误:“]”标记之前的预期主表达式(C++)
【发布时间】:2014-10-12 22:11:03
【问题描述】:

我很难处理不断弹出的错误。这是一个家庭作业,其中很大一部分包含在一个单独的 .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 = (unsigned int*)arrayOf。为什么你觉得你需要这对空括号?这不是有效的语法。并使arrayOf 成为unsigned int 的数组(或者m_storageint*),这样就不需要演员表了。哦,当构造函数返回时,arrayOf 将被销毁,留下 m_storage 一个悬空指针。
  • 你为什么要创建一个本地数组?你不应该只是m_storage = new unsigned int [INIT_SIZE];

标签: c++ list pointers


【解决方案1】:
m_storage = arrayOf[];

语法无效。

m_storage = arrayOf;

会从正确的轨道开始(int [] 衰减到 int*)但仍然存在问题,因为 m_storage 被定义为:

unsigned int *  m_storage;

因此m_storage 指向的任何数据都应该是unsigned,这要么需要强制转换:

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;
}

如果你这样做了,你应该全程执行rule of three (or five)。

【讨论】:

    【解决方案2】:

    重写此语句

    m_storage = arrayOf[];  
    

    作为

    m_storage = reinterpret_cast<unsigned int *>( arrayOf );  
    

    虽然m_storage 的类型为unsigned int * 看起来很奇怪,但您正试图将int * 类型的对象分配给它。

    正如 hvd 所指出的,您正在将本地数组的地址分配给数据成员 m_storage。所以这个函数整体是错误的,因为退出函数后数组会被销毁,指针也会失效。

    【讨论】:

    • m_storage 将指向一个本地数组,该数组在构造函数结束后被销毁,因此这不足以使其实际工作。
    猜你喜欢
    • 2015-03-31
    • 2012-07-08
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2013-01-13
    • 2017-09-24
    相关资源
    最近更新 更多