【问题标题】:Can't assign a value to int which inside the class [closed]无法为类内的 int 赋值[关闭]
【发布时间】: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

【问题讨论】:

  • 你超出了stackSize20,你正在写 21 个元素。
  • 解决了这个问题。谢谢
  • 还有一个问题 - 您的代码没有给出“堆栈溢出”错误消息或日志条目。
  • 警告:#define Size 20 存在一定风险。大小是一个相当常见的词,Size 宏会在程序编译之前悄悄地用 20 替换它的所有外观,如果你重用Size,会导致一些非常奇怪的编译器错误。更喜欢使用constexpr int Size = 20;
  • 请不要在问题标题中加上“已解决”。如果某个答案解决了您的问题,只需将该答案标记为已接受。

标签: c++ stack


【解决方案1】:

你超越了stackSize20,你正在写 21 个元素。

您的for 循环条件应该是i &lt; Size,而不是i &lt;= Size

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2016-08-16
    相关资源
    最近更新 更多