Re: Compilation errors in a vector problem
* Ankur Arora:
While coding an algorithm for the following problem, there are a few
compilation errors that I don't completely understand. The errors
are:-
error C2839: invalid return type 'Human **' for overloaded 'operator -
'
error C2039: 'PrintFamilyTree' : is not a member of
'std::_Vector_iterator<_Ty,_Alloc>'
1> with
1> [
1> _Ty=Human *,
1> _Alloc=std::allocator<Human *>
1> ]
I think C2839 probably triggers C2039, however I'm unable to pinpoint
the problem.
Here's the code and solution.
-----------------------------------------------------------------------------------------------------------
Implement method PrintFamilyTree() that prints out the Name and
Generation of the tree.
Output should resemble
Name: Jan Generation:0
Name: Mike Generation:1
Name: Greg Generation:2
Name: Carol: Generation: 2
Name: Peter Generation: 3
Name: Marcia Generation: 3
Name: Bobby Generation: 1
class Human : public std::vector<Human *>
{
public:
Human(const std::string &name) : m_Name(name) {};
virtual void PrintFamilyTree(const short &generation = 0) const;
protected:
std::string m_Name;
};
class Male: public Human
{
public:
Male(const std::string &name) : Human(name) {};
};
class Female: public Human
{
public:
Female(const std::string &name) : Human(name) {};
};
void main()
Your instructor or book should not teach you such bad habits.
'void' is not permitted as result type of 'main'.
Not in C, not in C++.
Use 'int main'.
{
Male m1("Mike"), m2("Greg"), m3("Peter"), m4("Bobby");
Female f1("Carol"), f2("Marcia"), f3("Jan");
m1.push_back(&m2);
f1.push_back(&m3);
f1.push_back(&f2);
m1.push_back(&f1);
f3.push_back(&m1);
f3.push_back(&m4);
f3.PrintFamilyTree();
}
Solution
------------
void PrintFamilyTree(const short& generation)
This does not match the declaration in the class. Worse, you're not definining
the class' member routine but some free-standing routine.
To get going on this, replace above with
void Human::PrintFamilyTree(const short& generation) const
The logic below is sound, i.e. it'll work, but the coding is ungood.
You'll get a host of compilation errors. Just fix them one by one.
{
printf("Name : %s Generation = %d\n", m_Name.c_str(),generation);
vector<Human*>::iterator it;
for (it = this.begin(); it< this.end() ;it++)
{
it->PrintFamilyTree(generation+1);
}
}
Cheers & hth.,
- Alf