【发布时间】:2015-04-18 09:45:07
【问题描述】:
我刚刚在一个类中编写了堆栈数据结构的简化实现,但整数数组的处理方式我似乎无法理解。
与push() 中相同的 sn-p 代码将给出我期望的行为,但在此程序中,在某个数组位置分配一个值会将值分配给索引变量>
#include <iostream>
using namespace std;
class stack
{
public:
stack(int size)
{
ar_size = size - 1;
array[ar_size];
index = 0;
}
void push(int value)
{
cout << "index; " << index << endl; //will output 0
cout << "value: " << value << endl; //will output 8
array[index++] = value;
cout << "index; " << index << endl; //will output 8
cout << "value: " << value << endl; //will output 8
cout << "array: " << array[index] << endl; //will output what seems to be a memory address
}
int pop()
{
cout << "index; " << index << endl; //will output 8
return array[index--];
}
private:
int ar_size;
int array[];
int index;
};
int main()
{
stack tower(64);
tower.push(8);
int r = tower.pop();
cout << "pop: " << r << endl; //will output what seemed to be a memory address
return 0;
}
【问题讨论】:
-
这个语句实际上应该做什么:
array[ar_size];?我有一种感觉,它并没有像你想象的那样做。 -
启用编译器警告 + 阅读并理解警告 = 利润!
-
@πάντα ῥεῖ 我明白你的意思,我在私有定义中声明数组大小时遇到了一个错误,最终犯了这个错误。那么,我应该如何以及在哪里尝试声明数组大小?
-
@maja 最好使用
std::vector<int>,并在构造函数成员初始化列表中使用ar_size对其进行初始化:std::vector<int> array;stack(int size) : array(size) { // ... -
@Hiroaki 我不确定我应该期待什么结果,如果我在构造函数中尝试这个程序会崩溃,如果我在私有部分尝试它,我会得到与尝试设置相同的错误 @ 987654328@ with a size: 无效使用非静态数据成员 stack::ar_size`。