Consider a class A: class A { public: string names; //data .....................
ID: 3615181 • Letter: C
Question
Consider a class A:class A {
public:
string names; //data
..................... //member functions as necessary
}
Suppose you want to build a Stack class consisting of Aobjects, with maximum prescribed capacity.
class Stack{
public:
int top; //top of the stack, bottomis 0
A data[MAX_CAPACITY]; //stack ismodeled as an array of A objects
bool push(A); //push onto the stack- return success or failure
A pop( ); //pop from stack - returnthe top of the stack
Stack reverse( ); //returns a newstack with elements in reverse order
Stack( ){}
};
Write the necessary C++ code, and test it with a main( )function.
Explanation / Answer
#include<iostream>
#define MAX_CAPACITY 20
using namespacestd;
class A {
public:
string names; //data
A(){}
A(string s)
{
names =s;
}
string toString()
{
return names;
}
// ..................... //member functions as necessary
};
//Suppose you want to build a Stack class consisting of Aobjects, with maximum prescribed capacity.
class Stack
{
public:
int top; //top of the stack, bottomis 0
Adata[MAX_CAPACITY]; //stack is modeled as an array of Aobjects
bool push(A &a){
if(top==MAX_CAPACITY)
return false;
top++;
data[top]=a;
return true;
} //push onto the stack - return success or failure
A pop(){
if(top==-1)
return data[0];
else
return data[top--];
} //pop from stack - return the top of the stack
Stack reverse( ) //returns a newstack with elements in reverse order
{ Stack p;
int i=0;
for(i=top;i>=0;i--)
p.push(data[i]);
return p;
}
Stack(){
top=-1;
}
};
int main ()
{
A a("one");A b("two");A c("three");
Stack s;
s.push(a);
s.push(b);
s.push(c);
cout<<s.pop().toString()<<endl;
cout<<s.pop().toString()<<endl;
cout<<s.pop().toString()<<endl;
cout<<endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.