xcode sort() - 没有用于调用“交换”的匹配函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28761802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort() - No matching function for call to 'swap'
提问by Magnus W
Just spent about an hour trying to figure out why I would get 20 error messages of the type "Semantic issue - no matching function for call to 'swap'"
when I try to build the following class (in XCode).
刚刚花了大约一个小时试图弄清楚为什么"Semantic issue - no matching function for call to 'swap'"
当我尝试构建以下类(在 XCode 中)时会收到 20 条该类型的错误消息。
test.h
测试.h
#include <iostream>
#include <string>
#include <vector>
class Test{
std::vector<std::string> list;
void run() const;
static bool algo(const std::string &str1, const std::string &str2);
};
test.cpp
测试.cpp
#include "test.h"
void Test::run() const {
std::sort( list.begin(), list.end(), algo );
}
bool Test::algo(const std::string &str1, const std::string &str2){
// Compare and return bool
}
Most of the people with the same problem seem to have made their algorithm a class member instead of a static member, but that is clearly not the problem here.
大多数遇到同样问题的人似乎将他们的算法设为类成员而不是静态成员,但这显然不是这里的问题。
回答by Magnus W
It turns out it's a very simple problem, but not very obvious to spot (and the error message doesn't do a very good job in helping out either):
事实证明这是一个非常简单的问题,但不是很明显(并且错误消息在帮助方面也没有做得很好):
Remove the const
declaration on run()
- voilá.
删除const
关于run()
- voilá的声明。
回答by Vlad from Moscow
The compiler refers to swap
because std::sort
internally uses function swap. However as member function run
is declared as constant function
编译器引用是swap
因为std::sort
内部使用函数swap。但是由于成员函数run
被声明为常量函数
void run() const;
then the object of the class itself is considered as a constant object and hence data member list also is a constant object
那么类本身的对象被认为是一个常量对象,因此数据成员列表也是一个常量对象
std::vector<std::string> list;
So the compiler tries to call swap
with parameters that are constant references or even are not references and can not find such a function.
因此,编译器尝试swap
使用常量引用甚至不是引用的参数进行调用,并且找不到这样的函数。