我很难遇到一个不断弹出的错误。这是一个家庭作业,其中很大一部分都包含在一个单独的.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;
}
出于某种原因,我得到编译器期望在指示的行上的']'标记之前的主表达式的错误。我已经完成了我的笔记并完成了一些谷歌搜索,看起来这似乎是声明一个数组并用预定义的指针指向它的方式,不是吗?谁能帮我解决这个问题?谢谢。
答案 0 :(得分:0)
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)。
答案 1 :(得分:-1)
重写此声明
m_storage = arrayOf[];
作为
m_storage = reinterpret_cast<unsigned int *>( arrayOf );
虽然m_storage
类型为unsigned int *
并且您尝试为其分配int *
类型的对象,但看起来很奇怪。
正如 hvd 指出的那样,您正在为数据成员m_storage分配本地数组的地址。所以有趣的是整个错误,因为退出函数后数组将被销毁,指针将无效。