存储在基类数组中的子模板可以使用重载的虚函数吗?
为了简化处理继承的家庭作业问题,我认为使用多态性来完成任务可能会更好。这不是必需的,但如果可能的话更有意义。然而,我遇到了符号错误,使其按照我认为应该的方式工作,或者仅调用基类定义。我想要基于要调用的对象的重载函数。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将把类型的事情放在一边,虽然我认为你可能不需要它,因此不需要模板......但是,这就是你需要的:
首先,向量应该是指针:
矢量<水果*>水果;
这可以防止 切片(对象的苹果部分被切掉)。
另外,现在您有了指针,您的循环将发生变化:
现在将根据您拥有的水果类型调用适当的
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:
This will now call the appropriate
Info
function for the type of fruit you have.