开发者

Can child templates stored in a base class array, use an overloaded virtual function?

In hope to simplify a homework problem dealing with inheritance, I thought it might be better to use polymorphism to accomplish the task. It isn't required, but makes much more sense if possible. I am, however, getting symbol errors making it work as I thought it should or just the base class definition is called. I want the overloaded function based on the object to be called.

template <class T>
class Fruit {
  private:
    int count;
    T type;
  public:
    virtual void Info();
};

template <class T>
class Apple : public Fruit<T> {
  private:
    int variety;
  public:
    void Info()开发者_JAVA百科;
};

// more fruit-child classes

vector<Fruit<int> > fruits; // contains object of various derived types

...

for(int i=0; i<fruits.size(); i++
    fruits[i].Info();


I'm going to leave the type thing aside, though I think you probably don't need it and therefore don't need the template... but, here's what you need:

First, the vector should be of pointers:

vector<Fruit<int> *> fruits;

this prevents slicing (where the Apple part of the object is cut off).

Also, now that you have pointers, your loop will change:

for(int i=0; i<fruits.size(); i++)
    fruits[i]->Info();

This will now call the appropriate Info function for the type of fruit you have.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜