如何使用方法覆盖在输出屏幕上显示堆栈整数值

How to display the stack integer values on the output screen using method overriding?

本文关键字:显示 堆栈 整数 屏幕 输出 使用方法 覆盖      更新时间:2023-10-16

最近,我的实验室讲师通过使用方法重写的概念(我们目前正在研究继承(,给了我以下要运行的堆栈代码:

//4.3. This example demonstrates that how we can use the concept of Overriding.
#include<iostream>
#include<conio.h>
using namespace std;
class myStack {
protected:  //NOTE: Can't be private because only my child class should have access to it
enum {
maximumnumberofboxes = 3 
}; // enumerated is used before a user defined variable (maximumnumberofboxes) that contains a collection of built in datatypes. 
//I have used it to tell the size of my stack array
int stack[maximumnumberofboxes]; // my stack array of integers
int topvalue;
//Index to top of stack. An index accesses a specific element in my stack array (in this case, the top value)
public:
Stack() //my stack constructor
{
topvalue = -1;  
}
void push(int valueinbox) //Define a function that pushes the value of a specific element in the stack space
{
stack[++topvalue] = valueinbox; //put the value on stack
}
int pop()  //Define a function that pulls off the value of a specific element in the stack space
{
return stack[topvalue--]; //take number off stack
}
};

class childStack : public myStack //Single Inheritance
{
public:
void push(int valueinbox)
{ //put the value on stack
if(topvalue >= maximumnumberofboxes-1) //error if stack full
{
cout<<"topvalue = "<<valueinbox;
cout<<"ntopvalue= "<<topvalue;
cout << "nError: stack is full";
exit(1);
}
cout<<"ntopvalue= "<<topvalue;
cout<<"ntopindex= "<<valueinbox;
myStack::push(valueinbox); //call push() function in myStack class using unary scope operator
}
int pop() //call pop() function to pull value off my stack
{
if(topvalue < 0) //shows error if my stack is empty
{ 
cout << "nError: stack is emptyn";
exit(1);
}
return myStack::pop(); //call pop() in myStack class
}
};
int main()
{
childStack s1;
s1.push(11); //push some values onto child stack
s1.push(22);
s1.push(33);
cout << endl << s1.pop(); //pop some values from child stack
cout << endl << s1.pop();
cout << endl << s1.pop();
cout << endl << s1.pop(); //oops, popped one too many...
cout << endl;
system("pause");
getch();
return 0;
}

我的输出屏幕显示以下内容:

topvalue=11
topvalue=4249067
Error: stack is full

我想知道如何在输出屏幕上显示主函数(11,22,33(中提到的三个整数,而不会得到任何垃圾值?

我可以看到您的代码有几个问题:

  1. 我假设Stack()是类myStack的构造函数,对吗?为了实现这一点,它必须与您的类(myStack()(具有相同的名称。我不确定这些代码是如何在你的机器上编译的
  2. 您没有初始化数组int stack[maximumnumberofboxes]。所以一开始它可能会有一些垃圾值

注意:在这一行cout << endl << s1.pop(); //oops, popped one too many...上,您的程序将退出,因此您将无法访问system("pause");并查看控制台上实际打印的内容。