class Person {
private:
char* name;
int numChildren;
Person** childrenList;
public:
Person(char* name);
~Person();
// member functions
// ...
};
Suppose I create a
Person
by this code:Person* me = new Person("Alex");
,Alex
's descendants' object will also be created. For a specific instance, the structure will be like this:
I'd like to implement a function const Person* Person::findPerson(const Person* thisPerson, const char* target_name) const;
, that searches through all Person
to find the one with name
equals target_name
.
Here is my code:
const Person* Person::findPerson(const Person* thisPerson, const char* target_name) const {
if (strcmp(thisPerson->name(), target_name) == 0)
return thisPerson;
for (int i = 0; i < thisPerson->numChildren(); i++)
findPerson(thisPerson->childrenList[i], target_name);
}
I think the code will work but the compiler thinks it might returns nothing and don't let me compile it. And also, I don't know how to return nullptr
if nobody is found.
You need to:
return
the result of the recursive call, if successful return nullptr
if the person is not foundconst Person* Person::findPerson(const Person* thisPerson, const char* target_name) const {
if (strcmp(thisPerson->name(), target_name) == 0)
return thisPerson;
for (int i = 0; i < thisPerson->numChildren(); i++) {
const Person *p = findPerson(thisPerson->childrenList[i], target_name);
// Found in child tree? Return it (terminate recursion)
if (p) return p;
}
// Not found in this branch of the tree
return nullptr;
}
Although it seems a bit odd to pass a Person
pointer to a Person
member function. Also, numChildren
and name
are member variables, not functions.
Shouldn't it be:
const Person* Person::findPerson(const char* target_name) const {
if (strcmp(name, target_name) == 0)
return this;
for (int i = 0; i < numChildren; i++) {
const Person *p = childrenList[i]->findPerson(target_name);
// Found in child tree? Return it (terminate recursion)
if (p) return p;
}
// Not found in this branch of the tree
return nullptr;
}
And, I am obliged to ask why you are not using std::vector
and std::string
instead of arrays and char pointers?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.