我有一个 Animal 抽象类,我已经为它创建了子类,例如 Dog、Cat、Hamster 等。
我创建了一个方法,该方法遍历动物对象列表并对每个对象调用“描述”方法。 Describe是一个纯虚函数,已经在子类中实现。
我正在尝试创建一种方法来遍历任何动物容器并执行相同的操作。
这是我目前所拥有的:
template <typename Container>
void describe_all(Container &c) {
typedef typename Container::iterator Iter;
for (Iter p = c.begin(); p != c.end(); ++p)
}
我的脑子一片空白,我不确定如何合并动物类。我对 C++ 还是很陌生!
最佳答案
您已经有了答案。只需键入对 describe()
template <typename Container>
void describe_all(const Container &c) {
typedef typename Container::iterator Iter;
for (Iter p = c.begin(); p != c.end(); ++p)
(*p)->describe();
}
}
如果模板类型不提供 describe 方法,它将无法编译。
当然,如果你能使用C++11,这段代码会更干净。
template <typename Container>
void describe_all(const Container &c) {
for (auto ptr; c)
ptr->describe();
}
}
关于c++ - 创建一个方法来使用模板迭代自定义类的任何容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20135888/