gpt4 book ai didi

c++ - C++:返回具有继承对象的基于范围的循环迭代器

转载 作者:行者123 更新时间:2023-12-02 10:30:49 25 4
gpt4 key购买 nike

我有一个Vertex类,并且我想以特定方式对其邻居迭代,例如:

Vertex my_v;
for(const Vertex& v : my_v.get_neighbors_closer_than(10.0)
/* Some code on v*/
// And like this
for(const Vertex& v : my_v.get_neighbors_by_trigonometric_order()
/* Some code on v*/

为此,我创建了 自定义容器和迭代器,以迭代所需的方式。然后,我需要创建一个 继承DlnVertex : public Vertex,该类在大多数情况下对迭代函数具有相同的行为。因此,我想在我的 DlnVertex类中编写:
DlnVertex my_dv;
for(const DlnVertex& dv : my_dv.get_neighbors_closer_than(10.0))
/* Some code on dv*/
for(const DlnVertex& dv : get_neighbors_by_trigonometric_order())
/* Some code on dv*/

我的自定义迭代器返回 Vertex&,我需要在类 DlnVertex中使用 DlnVertex属性,而且我不知道如何 避免为继承类重写迭代器,因为它具有相同的行为。是否有任何 建议模式代码示例可以帮助我?

最佳答案

我找到了一种方法:为我的函数的返回类型模板基类:

template<typename VertexType>
class Vertex
{
/* ... */
MyContainer<VertexType> get_neighbors_closer_than(double rad);
}

然后通过将自身设置为模板类型来设计派生类:
class DlnVertex : public Vertex<DlnVertex>{/* ... */}

关于c++ - C++:返回具有继承对象的基于范围的循环迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62320645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com