错误:请求“..”中的成员'..',属于非类别类型
问题描述:
我使用STL priority_queue
并给出一个自定义比较器类,其构造函数接受指向存储优先级的向量的指针,因此 -错误:请求“..”中的成员'..',属于非类别类型
#include <iostream>
#include <queue> // std::priority_queue
#include <vector> // std::vector
using namespace std;
class CompareReachDist
{
const vector<float> *reach_dists;
public:
CompareReachDist(const vector<float> *input)
{
reach_dists = input;
}
bool operator() (const size_t &l, const size_t &r) const
{
return (reach_dists->at(l) > reach_dists->at(r));
}
};
typedef priority_queue<size_t, vector<size_t>, CompareReachDist> pq;
vector<float> reach_dists;
int main()
{
pq seeds(CompareReachDist(&reach_dists));
bool isEmpty = seeds.empty();
return 0;
}
然而,在编译我得到的错误:
error: request for member 'empty' in 'seeds', which is of non-class type 'pq(CompareReachDist&) {aka std::priority_queue<unsigned int std::vector<unsigned int>, CompareReachDist>(CompareReachDist&)}'
我要去哪里错了?
答
这是一个解析问题。让我们把它分解开:
CompareReachDist(&reach_dists)
你可能会认为这会创建一个临时CompareReachDist
与静态reach_dists
的地址。但是在总体声明中,它被解释为对CompareReachDist
的引用。奇怪,但是这是因为,大致来说,C++的语法支持函数声明来对象声明。以下
pq seeds(CompareReachDist(&reach_dists));
是一个函数的整体声明。它接受CompareReachDist&
并返回pq
。
您收到的错误很明显是因为一个函数没有可以调用的empty
成员。
自C++ 11以来的解决方案是倾向列表初始化,这会打破作为函数声明的歧义和解决方案。所以你可以这样做:
pq seeds{CompareReachDist{&reach_dists}};
并得到一个对象,如人们所期望的那样。
啊,是的。我现在看到它。你认为我应该重构我的对象声明,以便编译器不再将它用于函数声明吗? –
@ ameya.dubey - 好的,更喜欢C++ 11初始化语法。或者为'CompareReachDist'参数引入一个命名变量。 – StoryTeller
@ ameya.dubey - 确实如此。很高兴有帮助。 – StoryTeller