存储在基类数组中的子模板可以使用重载的虚函数吗?

发布于 2024-09-28 19:44:43 字数 557 浏览 6 评论 0原文

为了简化处理继承的家庭作业问题,我认为使用多态性来完成任务可能会更好。这不是必需的,但如果可能的话更有意义。然而,我遇到了符号错误,使其按照我认为应该的方式工作,或者仅调用基类定义。我想要基于要调用的对象的重载函数。

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();
};

// 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();

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();
};

// 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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妳是的陽光 2024-10-05 19:44:43

我将把类型的事情放在一边,虽然我认为你可能不需要它,因此不需要模板......但是,这就是你需要的:

首先,向量应该是指针:

矢量<水果*>水果;

这可以防止 切片(对象的苹果部分被切掉)。

另外,现在您有了指针,您的循环将发生变化:

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

现在将根据您拥有的水果类型调用适当的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文