gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:04:47 25 4
gpt4 key购买 nike

最近我的实验室导师通过使用方法覆盖的概念(我们目前正在研究继承)在堆栈上给了我以下代码来运行:

//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 empty\n";
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 的构造函数正确的?那么要实现它必须与您的类(class)同名( myStack() )。我不确定这段代码是如何在你的机器上编译的。
  2. 你没有初始化你的数组int stack[maximumnumberofboxes] .所以一开始它可能会有一些垃圾值(value)。

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

关于c++ - 如何使用方法覆盖在输出屏幕上显示堆栈整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58936145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com