无法为堆栈赋值
Unable to assign values to stack
这是我的堆栈实现的代码
class stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i=0; i < 10; i++)
{
arr[i] = 0;
}
return 0;
}
//further code below
这是显示Stack的方法
void disp()
{
for (int i=9; i >= 0; i--)
{
cout<<arr[i]<<endl;
}
}
当我使用 class 堆栈对象调用 disp() 方法时,它正在打印这些值:
16, 0, 14882528, 0, 34, 0, 8, 0, 4199705, 0
但是我已经在 Stack() 构造函数中为 arr[10] 的所有值分配了 0。
为什么会这样?
修复输入错误并删除 return“解决”问题。但是您的输出根本无法重现:
#include <iostream>
class Stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i=0; i < 10; i++)
{
arr[i] = 0;
}
}
//further code below
void disp()
{
for (int i=9; i >= 0; i--)
{
std::cout << arr[i] << std::endl;
}
}
};
int main()
{
Stack s;
s.disp();
}
我运行你的代码如下:
#include <iostream>
class Stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i = 0; i < 10; ++i)
{
arr[i] = 0;
}
// return 0; NOTE: constructor could not return a value
}
void disp()
{
for (int i = 9; i >= 0; --i)
{
std::cout << arr[i] << std::endl;
}
}
};
int main()
{
Stack s1;
s1.disp();
return 0;
}
它给了我这些:
$ ./a.exe
0
0
0
0
0
0
0
0
0
0
真不知道你在问什么
这是我的堆栈实现的代码
class stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i=0; i < 10; i++)
{
arr[i] = 0;
}
return 0;
}
//further code below
这是显示Stack的方法
void disp()
{
for (int i=9; i >= 0; i--)
{
cout<<arr[i]<<endl;
}
}
当我使用 class 堆栈对象调用 disp() 方法时,它正在打印这些值:
16, 0, 14882528, 0, 34, 0, 8, 0, 4199705, 0
但是我已经在 Stack() 构造函数中为 arr[10] 的所有值分配了 0。 为什么会这样?
修复输入错误并删除 return“解决”问题。但是您的输出根本无法重现:
#include <iostream>
class Stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i=0; i < 10; i++)
{
arr[i] = 0;
}
}
//further code below
void disp()
{
for (int i=9; i >= 0; i--)
{
std::cout << arr[i] << std::endl;
}
}
};
int main()
{
Stack s;
s.disp();
}
我运行你的代码如下:
#include <iostream>
class Stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i = 0; i < 10; ++i)
{
arr[i] = 0;
}
// return 0; NOTE: constructor could not return a value
}
void disp()
{
for (int i = 9; i >= 0; --i)
{
std::cout << arr[i] << std::endl;
}
}
};
int main()
{
Stack s1;
s1.disp();
return 0;
}
它给了我这些:
$ ./a.exe
0
0
0
0
0
0
0
0
0
0
真不知道你在问什么