+ 1
Class templates C++
This was the assignment and examples of the corrected code would be more helpful than observations. Thanks everyone! 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. The given code declares a Queue class with the corresponding methods for integers. Change the class to convert it into a class template, to support any type for the queue and so that the code in main runs successfully. https://code.sololearn.com/ck3dtWEIDTYX/?ref=app
10 Réponses
+ 3
https://code.sololearn.com/cxVHAI7LjnvI
+ 2
Put the same for add item function like :
void add(T elem) {
arr[count] = elem;
count++;
}
// only you adding elements are defined at object declaration.
// first object adds strings..
// second object adds all ints..
+ 2
#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;
}
+ 1
size, index types must be int.. Not T
Remove count method. No need.
Also, 2nd object must be <int> not <T>
Hope it helps..
+ 1
Updated code that throws latest error
#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) {
}
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;
}
+ 1
the code now runs with changing add(int) to add( T), but the test case is incorrect and hidden. Any ideas?
0
Line 27 error occurs
Invalid conversion from ' const char*' to 'int'
What does that mean?
0
Great!
Thanks for helping figure this out.
0
Is it solved now?
edit: seems done.
you're welcome..
0
HI everyone
@privetin your code https://www.sololearn.com/compiler-playground/cxVHAI7LjnvI
should work
but the test fails... any idea ?
I open a "bug report" to sololearn