#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class sum
{
public:
sum()
{
}
~sum()
{
}
bool cmp(int x,int y)
{
return x > y;
}
void data()
{
vector<int>test;
test.push_back(5);
test.push_back(1);
test.push_back(9);
sort(test.begin(),test.end(),cmp);
cout<<test[0]<<endl;
cout<<test[1]<<endl;
cout<<test[2]<<endl;
}
};
void main()
{
sum a;
a.data();
}
sort第三个参数比较函数,怎样调用其他类的函数?
是这样的,我只是随便打了一个例子,其实vector里面存了一个结构体,所以我必须写一个比较函数,但是我发现在类里面这样调用时错误的,求它的正确调用方法
追答那你要把类方法定义成静态的,然后用sum::cmp引用,某些编译器可能要用&(sum::cmp)
#include<iostream>真厉害,再请教一下,为啥它要设置为静态呢
追答静态成员不依赖于对象存在,它是属于类的,没有实例对象时就有静态成员了
因为非静态成员必须随对象产生,所以用::是无法确定是哪个对象的