Suppose I have a simple composite pattern structure:
abstract class User
leaf class PersonalUser
composite class GroupUser
with a std::vector<User*> users
container as its member variable
and a method bool GroupUser::findUser(User* u)
which returns true
if the user u
is found in the users
container (which naturally consists of other PersonalUser
or GroupUser
objects)
Now, I'd like to define that function recursively of course, so I need to go through each User
in users
vector, and compare with u
, but I won't know if the User
is a PersonalUser
or GroupUser
, so my question is:
Do I have to define a virtual function char User::returnType()
which will tell me which type of User
it is, or is there a better/smarter way to go down the tree and look for the User
?
ps there is of course a method like bool areEqual(User*, User*)
by which we can compare users :)
You can add the FindUser member function as a virtual to the abstract class User, and make it return true if the user being searched for is the current user (Personal or Group).
In GroupUser you can override FindUser and delegate any call to all the contained Users if the User being searched for isn't the current GroupUser.
As MadKeithV said, you declare the virtual function findUser(User*u) in the interface, then:
bool
User::findUser(User*u) {
return u == this;
}
and
GroupUser::findUser(User *u) {
for (// loop on your users)
if (currentUser.findUser(u))
return true;
}
}
You can use eg dynamic_cast<>()
to check if a User*
is really a GroupUser
or not, like this:
GroupUser* groupUser = dynamic_cast<GroupUser*>(userPointer);
If it returns a null pointer, then userPointer
is not a GroupUser
.
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.