0

当我尝试使用自定义比较器对成分进行排序时,出现此编译器错误。

kitchen.cpp: In member function ‘void Kitchen::printContents(std::ofstream&)’:
kitchen.cpp:172: error: no matching function for call to ‘std::list<Ingredient, std::allocator<Ingredient> >::sort(<unresolved overloaded function type>)’
/usr/include/c++/4.2.1/bits/list.tcc:271: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = Ingredient, _Alloc = std::allocator<Ingredient>]
/usr/include/c++/4.2.1/bits/list.tcc:348: note:                 void std::list<_Tp, _Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = bool (Kitchen::*)(const Ingredient&, const Ingredient&), _Tp = Ingredient, _Alloc = std::allocator<Ingredient>]

这是导致它的代码:

bool sortFunction(const Ingredient a, const Ingredient b)
{
    if (a.getQuantity() < b.getQuantity())
        return true;
    else if (a.getQuantity() == b.getQuantity())
    {
        if (a.getName() < b.getName()) return true;
        else return false;
    }
    else return false;
}

void Kitchen::printContents(std::ofstream &ostr)
{
    ostr << "In the kitchen: " << std::endl;

    ingredients.sort(sortFunction);

    std::list<Ingredient>::iterator itr;
    for (itr = ingredients.begin(); itr != ingredients.end(); ++itr)
    {
        ostr << std::setw(3) << std::right << itr->getQuantity() << " " 
        << itr->getName() << std::endl;

    }
}
4

4 回答 4

3

可能有另一个sortFunction地方(例如 in Kitchen)导致上述错误。

尝试

ingredients.sort(::sortFunction);

类似于这个问题

此外,为了获得良好的编码习惯,您可能需要更改

bool sortFunction(const Ingredient a, const Ingredient b)

bool sortFunction(const Ingredient &a, const Ingredient &b)

第一个是传递对象的副本,第二个只是传递对它的引用。

于 2013-02-28T18:22:11.373 回答
2

看起来您在 Kicthen 中有一个名为 sortFunction 的方法,编译器无法选择合适的方法。你可以试试这个:

list.sort( ::sortFunction );

要解决它,或者如果您提供的功能假设是 Kitchen 类的方法,您需要修复它。

顺便提一句:

if (a.getName() < b.getName()) return true;
else return false;

是相同的:

return a.getName() < b.getName();
于 2013-02-28T18:27:02.907 回答
1

我的猜测是你声明了一个成员函数Kitchen::sortFunction。在另一个成员函数(例如printContents)中,将隐藏您要使用的非成员函数。

错误消息表明是这种情况;它正在尝试sort为成员函数类型实例化bool (Kitchen::*)(const Ingredient&, const Ingredient&)

如果成员函数不应该存在,则删除声明。如果是,则重命名其中一个函数,或将非成员函数称为::sortFunction.

于 2013-02-28T18:31:47.943 回答
0

您的排序功能是:

bool sortFunction(const Ingredient a, const Ingredient b)

但它可能应该是:

bool sortFunction(const Ingredient &a, const Ingredient &b)

(注意参考文献)

此外,正如已经提到的,您的 Kitchen 类已经有一个名为 sortFunction() 的函数并且它具有优先权,因此请使用 ::sortFunction() 或为每个函数指定一个唯一且更具描述性的名称。

如果 Kitchen::sortFunction()您想要的,它需要是一个静态成员函数。

于 2013-02-28T18:42:09.263 回答