+ 1
your queue problem <template>
// i tried to fix it but i do not know what wrong with it. any one can help please? #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; } void add(int elem) { arr[count] = elem; count++; } void get(int index) { cout << arr[index]<<endl; } }; template<class T> T Queue<T>::add( ){ } T Queue<T>::get(){ } 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; }
6 Answers
+ 3
Here is my solution:
The variable type of arr (array) and elem (item in array) needs to be generic so both string and integer type parameters can be passed through. Other variables like count, size and index needs to remain as integer types.
#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
You have two methods of void type, but when you are defining them, you assigned type T as the return type. Change it to void and give these methods the body if needed
If it is not problem, then share your code in code playground so it will be easy for us to check the errors etc
0
i will thanks
0
Michal Doruch I have a similar issue with this practice code. I changed what I think is the return type to void but get the error âNo declaration matches void Queue <T>::add(){}â. Iâll post my code in the next comments. Any guidance is appreciated. Thanks!
0
#include <iostream>
using namespace std;
template<class T>
class Queue{
private:
int *arr;
int count;
public:
Queue(int size) {
arr = new int[size];
count = 0;
}
void add(int elem) {
arr[count] = elem;
count++;
}
void get(int index) {
cout << arr[index]<<endl;
}
};
template <class T>
void Queue <T>::add(){}
void Queue <T>::get(){}
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
Thanks!