I am learning C in school and in my homework, my task is to create the FooClass for these:
int main()
{
int x[] = {3, 7, 4, 1, 2, 5, 6, 9};
FooClass<int> ui(x, sizeof(x) / sizeof(x[0]));
std::string s[] = {"Car", "Bike", "Bus"};
FooClass<std::string> us(s, sizeof(s) / sizeof(s[0]));
}
then modify the code so it can write out the size of the lists and the elements of the lists.
I managed to write the code for the size function. But I am struggling with the element part, getting an
error: missing template arguments before '.' token.
Here is my code so far:
template <typename T>
class FooClass
{
private:
T *items;
int itemsSize;
bool mergeOn;
public:
FooClass(T items[], int itemsSize)
{
items = new T[itemsSize];
this->itemsSize = itemsSize;
};
int getItemsSize()
{
return this->itemsSize;
}
void print(const FooClass <T>& items)
{
for (int i=0; i< items.getItemsSize(); i)
{
std::cout<<items[i]<<std::endl;
}
}
};
int main()
{
int x[] = {3, 7, 4, 1, 2, 5, 6, 9};
FooClass<int> ui(x, sizeof(x) / sizeof(x[0]));
std::string s[] = {"Car", "Bike", "Bus"};
FooClass<std::string> us(s, sizeof(s) / sizeof(s[0]));
std::cout<<ui.getItemsSize()<<std::endl;
FooClass.print(us); //this is where I get the compilation error.
}
How should I implement the print function?
CodePudding user response:
Your constructor is not copying the source elements into the array that it allocates. And, you need a destructor to free the allocated array when you are done using it.
And, your print()
method is not static
, so it should act on this
instead of taking a FooClass
object as a parameter.
Try this:
template <typename T>
class FooClass
{
private:
T *m_items;
int m_itemsSize;
bool m_mergeOn;
public:
FooClass(T items[], int itemsSize)
{
m_items = new T[itemsSize];
for (int i = 0; i < itemsSize; i) {
m_items[i] = items[i];
}
m_itemsSize = itemsSize;
};
~FooClass()
{
delete[] m_items;
}
int getItemsSize() const
{
return m_itemsSize;
}
void print() const
{
for (int i = 0; i < m_ItemsSize; i)
{
std::cout << m_items[i] << std::endl;
}
}
};
int main()
{
int x[] = {3, 7, 4, 1, 2, 5, 6, 9};
FooClass<int> ui(x, sizeof(x) / sizeof(x[0]));
std::cout << ui.getItemsSize() << std::endl;
ui.print();
std::string s[] = {"Car", "Bike", "Bus"};
FooClass<std::string> us(s, sizeof(s) / sizeof(s[0]));
std::cout << us.getItemsSize() << std::endl;
us.print();
}