【问题标题】:C++ : Return an range based for loop iterator with inheritate objectsC ++:返回基于范围的具有继承对象的for循环迭代器
【发布时间】:2020-06-11 08:57:01
【问题描述】:

我有一个班级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*/

为此,我创建了 自定义容器和迭代器,它们按照我想要的方式进行迭代。然后,我需要创建一个 inheritateDlnVertex : 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 属性,但我不知道如何避免重写迭代器我的继承类,因为它会有相同的行为。是否有任何建议模式代码示例可以帮助我?

【问题讨论】:

  • 这个question 可能会有所帮助。
  • 谢谢,我可以写这样的东西,但我想在我的继承类中为函数get_neighbors_closer_than 和另一个。

标签: c++ inheritance iterator


【解决方案1】:

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

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

然后通过将自己设置为模板类型来设计我的派生类:

class DlnVertex : public Vertex<DlnVertex>{/* ... */}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多