Sep 3, 2014 at 12:18pm UTC
Hey guys, I'm struggling with the functionality of a certain function for a program I'm writing, the specification for the function is as follows:
name(): Should return the string “Drug: ” followed by the drug name and the the names of the components
inside brackets. If one of the components is a drug itself, the entire sub-drug and all its components
should also be added.
I'm struggling with the name() function as I do not yet fully understand the working of Vectors, any help on how to define this function will be greatly appreciated.
Drug.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#ifndef DRUG_H
#define DRUG_H
#include "Component.h"
#include <vector>
class Drug : public Component
{
public :
Drug(string name);
virtual ~Drug();
void administer();
string name();
void add(Component *component);
virtual void mix();
private :
vector<Component*> mComponents;
};
#endif
Drug.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include "Drug.h"
Drug::Drug(string name)
: Component(name)
{
}
Drug::~Drug()
{
vector<Component*>:: iterator it;
for (it = mComponents.begin(); it != mComponents.end(); ++it)
{
delete *it;
}
}
void Drug::administer()
{
cout << "Administering drug ..." << endl;
}
void Drug::add(Component *component)
{
mComponents.push_back(component);
}
//My attempt at defining the name() function, this is incorrect however.
//mName is a protected variable in the parent class.
string Drug::name()
{
string out = "Drug: " + mName + " [ " ;
for (int i = 0; i < mComponents.size(); ++i)
{
out += mComponents[i] + ", " ;
}
out += " ]" ;
return out;
}
void Drug::mix()
{
cout << "Mixing drug ..." << name() << endl;
}
Last edited on Sep 3, 2014 at 12:19pm UTC
Sep 3, 2014 at 12:44pm UTC
Please show the definition of Component.
Sep 3, 2014 at 12:52pm UTC
> this is incorrect however
¿in which way?
(compile error, runtime error, wrong output)
You may want virtual string name();
Also, take a look at smart pointers
Sep 3, 2014 at 1:34pm UTC
Why is Drug.h trying to include itself?
Sep 3, 2014 at 3:18pm UTC
It's not. The OP reversed the labels for the drug.h and drug.cpp snippets.
Sep 3, 2014 at 3:50pm UTC
@keskiverto, thank you so much! That helped a lot.