0
78.2 Practice - Your Queue!
You are making a queue management system and need to support different data types - for example, you should be able to queue names which are strings or integer numbers. So, you decide to make a Queue class template, which will store an array for the queue, and have add() and get() methods. You first create a class for integers only, to see if it works. My code as below, added template <class T> at 2 different places but it says it shadows the existing code.
3 Réponses
+ 5
#include <iostream>
using namespace std;
//change the class to a template
template <class T>
class Queue
{
private:
T *arr;
int count;
public:
Queue(int size) {
arr = new T[size];
count = 0;
}
void add(T elem) {
arr[count] = elem;
count++;
}
void get(int index) {
cout << arr[index]<<endl;
}
};
int main()
{
Queue<string> q(4);
q.add("James");
q.add("Andy");
q.add("Amy");
q.get(2);
Queue <int> n(2);
n.add(42);
n.add(33);
n.get(1);
return 0;
}
0
#include <iostream>
using namespace std;
//change the class to a template
template <class T>
class Queue
{
private:
int *arr;
int count;
public:
Queue(int size) {
arr = new int[size];
count = 0;
}
template <class T>
void add(int elem) {
arr[count] = elem;
count++;
}
void get(int index) {
cout << arr[index]<<endl;
}
};
int main()
{
Queue<string> q(4);
q.add("James");
q.add("Andy");
q.add("Amy");
q.get(2);
Queue <int> n(2);
n.add(42);
n.add(33);
n.get(1);
return 0;
}
0
Found the answer:
Change <int> to <T> except for <int count> and <int main>
Remove “template <class T>” before “void add(int elem)”