【发布时间】:2019-09-10 03:00:11
【问题描述】:
我设置了veriable,但是当我调用它时,它带有不同的veriable。 没有for循环它工作正常。但是当我添加for循环时,问题就出现了。
#define Size 20
class Stack{
private:
int stack[Size];
int top;
public:
Stack();
~Stack();
void info();
};
Stack::Stack(){
cout<<"The stack is beign created"<<endl;
cout<<"//////////////////////////"<<endl;
top = -1; // The problem is here <<
cout<<top<<endl;
for(int i = 0;i <= Size;i++){
stack[i] = 0;
};
cout<<top<<endl;
};
void Stack::info(){
cout<<top<<endl;
}
我的期望输出是:
The stack is beign created
//////////////////////////
-1
-1
-1
//////////////////////////
The stack is beign destroyed
当前代码的输出是:
The stack is beign created
//////////////////////////
-1
0
0
//////////////////////////
The stack is beign destroyed
【问题讨论】:
-
你超出了
stack。Size是20,你正在写 21 个元素。 -
解决了这个问题。谢谢
-
还有一个问题 - 您的代码没有给出“堆栈溢出”错误消息或日志条目。
-
警告:
#define Size 20存在一定风险。大小是一个相当常见的词,Size宏会在程序编译之前悄悄地用 20 替换它的所有外观,如果你重用Size,会导致一些非常奇怪的编译器错误。更喜欢使用constexpr int Size = 20;。 -
请不要在问题标题中加上“已解决”。如果某个答案解决了您的问题,只需将该答案标记为已接受。