传递类方法,而不是std::Sort中的函数 [英] passing a class method as opposed to a function in std::sort
本文介绍了传递类方法,而不是std::Sort中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在类中,我试图通过传递同一类的方法来对向量进行排序。但它在编译时会给出错误。有谁能说出问题出在哪里吗?谢谢!
它会显示以下错误:
bool (Sorter::)(D&, D&)' does not match
bool(Sorter::*)(D&;,D&;)‘
我还尝试使用sortBynumber(D const& d1, D const& d2)
#include<vector>
#include<stdio.h>
#include<iostream>
#include<algorithm>
class D {
public:
int getNumber();
D(int val);
~D(){};
private:
int num;
};
D::D(int val){
num = val;
};
int D::getNumber(){
return num;
};
class Sorter {
public:
void doSorting();
bool sortByNumber(D& d1, D& d2);
std::vector<D> vec_D;
Sorter();
~Sorter(){};
private:
int num;
};
Sorter::Sorter(){
int i;
for ( i = 0; i < 10; i++){
vec_D.push_back(D(i));
}
};
bool Sorter::sortByNumber(D& d1, D& d2){
return d1.getNumber() < d2.getNumber();
};
void Sorter::doSorting(){
std::sort(vec_D.begin(), vec_D.end(), this->sortByNumber);
};
int main(){
Sorter s;
s.doSorting();
std::cout << "
Press RETURN to continue...";
std::cin.get();
return 0;
}
推荐答案
使Sorter::sortByNumber
静态。因为它不引用任何对象成员,所以您不需要更改任何其他内容。
class Sorter {
public:
static bool sortByNumber(const D& d1, const D& d2);
...
};
// Note out-of-class definition does not repeat static
bool Sorter::sortByNumber(const D& d1, const D& d2)
{
...
}
您还应使用常量引用,因为sortByNumber
不应修改对象。
这篇关于传递类方法,而不是std::Sort中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文