2013-02-28 147 views
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; 

    } 
} 
+0

你怎么定义排序?错误是说你没有与之相匹配的电话。 – TopGunCoder 2013-02-28 18:21:51

+1

@TopGunCoder:'std :: list'有一个'sort()'函数,它需要一个比较器。 – 2013-02-28 18:25:49

+2

你有没有其他名字为'sortFunction'的函数? 'sortFunction'是'Kitchen'的非静态成员? – 2013-02-28 18:31:19

回答

3

可能有另一个sortFunction某处(例如,在Kitchen),这会导致上述错误。

尝试

ingredients.sort(::sortFunction); 

类似this question

而且,良好的编码习惯,你可能要更改

bool sortFunction(const Ingredient a, const Ingredient b) 

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

首先是通过在对象的副本,第二只传递给它的引用。

+1

你确定这个原因吗? – Slava 2013-02-28 18:28:00

+0

我以前就是这样,它给了我同样的错误。 :( – 2013-02-28 18:28:21

+0

@LoganShire请参阅编辑。 – Dukeling 2013-02-28 18:29:24

2

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

list.sort(::sortFunction); 

要解决这个问题,或者如果您提供的假设是厨房类的方法的功能,你需要解决这个问题。

BTW:

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

是一样的:

return a.getName() < b.getName(); 
1

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

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

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

0

你的排序功能是:

bool sortFunction(const Ingredient a, const Ingredient b) 

但是这或许应该是:

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

(注意参考)

此外,如前所述,您的厨房类已经有一个函数称为sortFunction(),它的优先级是,所以要么使用:: sortFunction(),要么为每个函数提供一个唯一的,更具描述性的名称。

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

相关问题