class Animal
{
};
class Herbivore:Animal
{
void eat();
};
class Carnivore:Animal
{
void eat();
};
class Food
{
bool bMeat;
bool bVegeable;
};
I start out this class and all of a sudden I don't know what to do to with the class Food, as I would like to print out the correct food type each "kind" of animal favors most.
Sorry my food class size is small but I can't delete it as my whole program requires it to distinguish the food type. I will not mind if you suggest 开发者_JS百科a different solution.
Since this is homework, I'm not going to post a code snippet, I'll just try to explain (and by trees, I assume you mean inheritance).
I see that you've fixed the animals not inheriting from Animal
which is good. However, to incorporate Food
into the mix, you probably want to have a member of Animal
(so every subclass of Animal
has to have it) that is a Food
called favouriteFood
or something similar, which is initialized in the constructor of each subclass of Animal
to that animal's favourite food.
The second thing I think you'll want to do is to make the member function eat
both virtual
and part of Animal
so that each subclass of Animal
has that member (and virtual so that when you call the function through an Animal*
or &
, it will call the correct version). Then make eat
have one parameter which is a Food
, the food they are eating.
Try something like bool eat(Food & food)
. In eat
you can then check if your animal likes it and either return false
or consume the food and return true
. It might also make sense to throw a bad_food
exception instead of the return value.
Here's what I would try:
class Food;
class Vegetable : Food { ; };
class Meat : Food { ; }
struct Animal
{
virtual void eat(const Food& f)
{;} // Stubbed.
};
struct Herbivore : Animal
{
virtual void eat(const Vegetable&) = 0;
};
struct Carnivore : Animal
{
virtual void eat(const Meat&) = 0;
};
struct Omnivore : Animal
{
void eat(const Food& f)
{ cout << "I'm not picky.\n"; }
};
I suggest you look up concepts such as double dispatch and Visitor Design Pattern.
精彩评论