【问题标题】:How to add handle as a class member, where class is used for template of heap?如何将句柄添加为类成员,其中类用于堆模板?
【发布时间】:2014-06-09 01:13:20
【问题描述】:

考虑一个简单的例子:

#include <boost/heap/fibonacci_heap.hpp>

class MyClass;

struct compare_distances
{
    bool operator()(const MyClass* n1, const MyClass* n2) const
    {
        return n1->distance > n2->distance;
    }
};

typedef boost::heap::fibonacci_heap<MyClass*, boost::heap::compare<compare_distances> > fib_heap;

class MyClass
{
    public:
        string name;
        double distance;
        fib_heap::handle_type handle;
};

我想以这种方式访问​​堆中 MyClass 对象的句柄。所以我转发声明 MyClass。但是编译器说: 错误:无效使用不完整类型“const class MyClass”compare_distances 中的return 行错误)。 如何解决?

有必要实现一个方便的对象网络,例如:

class MyClass
{
    public:
        string name;
        double distance;
        fib_heap::handle_type handle[4]; // handles for other objects of MyClass
};

【问题讨论】:

    标签: c++ boost heap handle fibonacci-heap


    【解决方案1】:

    如果您只是在 MyClass 之前声明比较器函子的 operator() 并在类定义之后定义它,则编译如下:

    class MyClass;
    
    struct compare_distances
    {
        inline bool operator()(const MyClass* n1, const MyClass* n2) const;
    };
    
    typedef boost::heap::fibonacci_heap<MyClass*, boost::heap::compare<compare_distances> > fib_heap;
    
    class MyClass
    {
    public:
        string name;
        double distance;
        fib_heap::handle_type handle;
    };
    
    bool compare_distances::operator()(const MyClass* n1, const MyClass* n2) const
    {
        return n1->distance > n2->distance;
    }
    

    请注意,我已将内联添加到函数中以避免链接器错误。 (结构中定义的成员函数是隐式内联的。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      相关资源
      最近更新 更多