show how its done please. here is the code. template<typename T> Bags<T>::Bags()
ID: 3601772 • Letter: S
Question
show how its done please. here is the code.
template<typename T>
Bags<T>::Bags()
{
count = 0;
for (int i = 0; i < 10; i++)
{
bgs[i] = bag;
bag[0] = 1;
count++;
}
}
template<typename T>
Bags<T>::~Bags()
{
for (int i = 0; i < 10; i++)
{
bgs[i] = NULL;
}
count = 0;
}
and bag.h
#include <iostream>
#include "bag.h"
template<typename T>
class Bags: private Bag<T>
{
public:
// constructor
Bags();
// destructor
~Bags();
private:
T bgs[10];
int count;
T bag;
};
#include "bags.cpp"
Sometimes one bag just isn't enough. Let's create a Bags class that allocates ten bags for the user via the array bgs. You are to complete the private member data in bags.h and write the default constructor and destructor in bags.cpp. The constructor should add the item 1 to each bag.Explanation / Answer
The question makes use of the Bag class , and those files bag.h and bag.cpp is not provided. I have assumed you have a function add() in bag which adds an item into the bag.
The Bags class constructor takes an item that should be added to each bag. So for example, you can create a Bags object of int type with 1 added to each bag.
Bags<int> b(1);
bags.h
#include <iostream>
#include "bag.h"
template<typename T>
class Bags:
{
public:
// constructor
Bags();
// destructor
~Bags();
private:
Bag<T> *bgs; //pointer to dynamically allocated array of Bag objects
};
#include "bags.cpp"
bags.cpp
template<typename T>
Bags<T>::Bags(T item) //accepts the item to be added to each bag
{
bgs = new Bag<T>[10]; //allocate dynamic memory
for(int i = 0; i < 10; i++) //for each of the 10 bags , add the item
bgs[i].add(item);
}
template<typename T>
Bags<T>::~Bags()
{
delete []bgs; //deallocate the dynamically created array
}
========
Hope the answer helped.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.