我知道我可以使用我的定义函数对数组进行排序,如下所示:
bool cmp(int a, int b){
return a > b;
}
class SortTest{
public :
void testSort(){
int a[] = { 1, 3, 4, 7, 0 };
int n = 5;
sort(a, a + n, cmp); //work
for (int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
};但是如果让SortTest类中的cmp函数运行,它就不能工作了。
class SortTest{
public :
bool cmp(int a, int b){
return a > b;
}
void testSort(){
int a[] = { 1, 3, 4, 7, 0 };
int n = 5;
sort(a, a + n, &SortTest::cmp); // not work
for (int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
};我定义了两个模板SortClass和SortClass2,比如大模板,SortClass2是use运算符(),SortClass是cmp,只有use运算符()才能工作。
template <class T> struct SortClass {
bool cmp (const T& x, const T& y) const { return x > y; }
};
template <class T> struct SortClass2 {
bool operator()(const T& x, const T& y) const { return x > y; }
};
class SortTest{
public :
bool operator() (const int& x, const int& y) const { return x > y; }
void testSort(){
int a[] = { 1, 3, 4, 7, 0 };
int n = 5;
//sort(a, a + n, &SortClass<int>::cmp); //not work
//sort(a, a + n, SortClass2<int>()); //work
sort(a, a + n, SortTest()); //work
for (int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
};那么,我的问题是,为什么SortTest类中的cmp函数不能工作,但是()是工作的呢?如果cmp函数不在类中,它就可以正常工作。非常感谢。
发布于 2016-01-18 04:09:21
问题是&SortClass<int>::cmp正在传递指向SortClass成员函数的指针,但是sort没有任何实例来调用成员函数。
只需尝试添加以下代码片段:
int i = 5, j = 10;
(&SortClass<int>::cmp)(i, j) // won't work
SortClass<int> test;
test.cmp(i,j) // will work because it is being called on an instance.如果将其更改为静态函数,则可以使其工作,如下所示:
bool cmp (const T& x, const T& y) const { return x > y; }至:
static bool cmp (const T& x, const T& y) { return x > y; }注意,函数参数和函数体之间的const必须删除,因为静态函数不能在此指针上工作。
另外,为什么要上这些课?C++的优点之一是,您可以混合编程范例,而不必在类中拥有所有的东西,比如在Java中。为什么不把它们作为免费功能呢?
发布于 2016-01-18 04:09:59
对于您的问题有几种解决方案,都有不同的注意事项:
发布于 2016-01-18 03:59:23
因为std::sort假设传递给它的比较函数对象可以通过语法(如comp(lht, rhs); )调用,而成员函数指针不能调用。调用它需要一个对象。
您可以使用fn或std:绑定作为一个词。
https://stackoverflow.com/questions/34846982
复制相似问题