【发布时间】:2013-11-16 03:22:58
【问题描述】:
我正在尝试重载 () 运算符,以便优先队列与我的 Cell 对象一起使用。
每个 Cell 对象都有以下功能:
static int GetCost(const Cell first, const Cell second);
这会将成本从first Cell 返回到second。
现在我有一个这样的优先级队列:
priority_queue<Cell*, std::vector<Cell*>, Comparator> path;
我的优先队列必须是指针队列。
我想根据单元格的成本(从GetCost() 返回)在优先级队列中添加单元格,所以在网上找到了一些示例后,我尝试这样做:
struct Comparator
{
bool operator()(const Cell lfs, const Cell rhs)
{
return Cell::GetCost(lfs, rhs) < Cell::GetCost(rhs, lfs);
}
};
但这给了我错误:
Error 4 error C2664: 'bool AI::Comparator::operator ()(const Cell,const Cell)' : cannot convert argument 1 from 'Cell *' to 'const Cell'
我已经试过改成这样了:
bool operator()(Cell* const lfs, Cell* const rhs)
{
return Cell::GetCost(*lfs, *rhs) < Cell::GetCost(*rhs, *lfs);
}
但这给了我一个更严重的错误:
Error 4 error LNK2019: unresolved external symbol "public: static int __cdecl Cell::GetCost(class Cell,class Cell)" (?GetCost@Cell@@SAHV1@0@Z) referenced in function "public: bool __thiscall AI::Comparator::operator()(class Cell * const,class Cell * const)" (??RComparator@AI@@QAE_NQAVCell@@0@Z)
我已经尝试过改变
static int GetCost(const Cell first, const Cell second)
到
static int GetCost(const Cell* first, const Cell* second)
我得到的错误是:
Error 4 error LNK2019: unresolved external symbol "public: static int __cdecl Cell::GetCost(class Cell const *,class Cell const *)" (?GetCost@Cell@@SAHPBV1@0@Z) referenced in function "public: bool __thiscall AI::Comparator::operator()(class Cell * const,class Cell * const)" (??RComparator@AI@@QAE_NQAVCell@@0@Z)
这是整个 GetCost:
static int GetCost(const Cell first, const Cell second)
{
int k;
for (k = 0; k < first.neighbors.size(); k++)
{
if (first.neighbors[k].cell->row == second.row &&
first.neighbors[k].cell->column == second.column)
{
return first.neighbors[k].weight;
}
}
}
我也试过把它改成指针,但是没用。
【问题讨论】:
-
错误信息会告诉你究竟出了什么问题,并给你一个(IMO)非常清楚的提示,告诉你该怎么做。始终阅读错误(和警告!)消息。
-
@JoachimPileborg 显然,我已经尝试了很多其他的东西,比如我刚刚编辑的那个,但我想发布最简单的错误以获得一些帮助。
-
您在哪里以及如何定义您的
GetCost函数? -
您确实在某处实现了
GetCost静态方法吗?顺便说一句,您可能希望将其更改为也使用指针,或者通过引用获取其参数。 -
这不能解决问题(这就是答案的目的),但你应该通过引用而不是值传递,即
const Cell &lfs而不是const Cell lfs(否则你会不必要地复制对象)。
标签: c++ data-structures compiler-errors operator-overloading priority-queue