首先描述一个情景:

先贴出代码:

class Solution
{
public:
bool compare(int a, int b)
{
return a > b;
} int function_t(vector<int> &numbers)
{
sort(numbers.begin(), numbers.end(), compare);
for (auto iter = numbers.begin(); iter != numbers.end(); ++iter)
cout<<*iter<<endl;
return ;
}
private:
int test = ;
};

类成员函数对数组进行排序,排序使用的是STL自带的sort函数。上述代码无法编译通过,因为对于sort而言,第三个参数是自定义的比较函数,其函数不能够为一个非静态类成员函数。

如果需要使用compare,可以有两种方案,第一种,将compare函数声明为全局函数;第二种,将compare函数设置为static静态函数。

方法1:

bool compare(int a, int b)
{
return a > b;
} class Solution
{
public:
int function_t(vector<int> &numbers)
{
sort(numbers.begin(), numbers.end(), compare);
for (auto iter = numbers.begin(); iter != numbers.end(); ++iter)
cout<<*iter<<endl;
return ;
}
private:
int test = ;
};

方法2:

class Solution
{
public:
static bool compare(int a, int b)
{
return a > b;
} int function_t(vector<int> &numbers)
{
sort(numbers.begin(), numbers.end(), compare);
for (auto iter = numbers.begin(); iter != numbers.end(); ++iter)
cout<<*iter<<endl;
return ;
}
private:
int test = ;
};

现在考虑,如果在compare函数中,需要使用类私有变量test,则上述两种方法都无法完成。对于类static成员函数,是不能够操作类成员函数和变量的(类成员函数的第一个默认参数是this指针,但static函数没有this指针),一般的做法,是将this指针传入static函数。例如:

static bool compare(int a, int b, Solution *arg)
{
Solution *p = (Solution *)arg;
cout<<p->test<<endl;
p->test++;
return a > b;
} compare(a, b, this);

这样在类静态函数compare中就可以操作当前对象的test变量。但对于sort排序函数而言,如何实现对this指针的传参?

解决方案:使用bind绑定器,关于bind绑定器的介绍就不在一一展开,这篇博文主要是阐述如何在类成员函数中操作类私有变量。

代码:

class Solution
{
public:
bool compare(int a, int b)
{
test++;
return a > b;
} int function_t(vector<int> &numbers)
{
auto ff = bind(&Solution::compare, this, placeholders::_1, placeholders::_2);
sort(numbers.begin(), numbers.end(), ff);
cout<<test<<endl;
for (auto iter = numbers.begin(); iter != numbers.end(); ++iter)
cout<<*iter<<endl;
return ;
}
private:
int test = ;
};

对于类中的非静态成员函数而言,其第一个参数是默认的this指针,接下来是显式声明的形参,通过bind绑定器,为函数compare设置默认参数,第一个为this,剩余两个为占位符,这样

在sort函数中直接调用新函数指针ff,就可调用compare并默认传入了当前对象的this指针。

最新文章

  1. redis-内存异常 Redis is configured to save RDB snapshots解决
  2. Oracle 优化 - CPU 问题
  3. std::map常用方法
  4. Jquery点击表格单位时选中其中的Radio的三个方法
  5. AngularJS recursive(递归)
  6. 2016 - 1 - 22 HTTP(一)
  7. typedef 和 define的区别
  8. c语言描述简单的线性表,获取元素,删除元素,
  9. C语言之猜数字游戏
  10. Poj 2777 Count Color(线段树基础)
  11. 安卓---achartengine图表----简单调用----使用view显示在自己的布局文件中----actionBar的简单设置
  12. MarsEdit快速插入源代码
  13. Java基础——输入输出
  14. Flutter 实现原理及在马蜂窝的跨平台开发实践
  15. cmake编译opencv时指定cuda版本
  16. VS2017项目程序打包成.msi或者.exe
  17. HDU3572构造图的模型
  18. 一本通1628X-factor Chain
  19. Scripting API Samples
  20. Spring Boot干货系列:(二)配置文件解析

热门文章

  1. bzoj4332[JSOI2012]分零食
  2. select模型的原理、优点、缺点
  3. [洛谷P5107]能量采集
  4. BZOJ3668:[NOI2014]起床困难综合症——题解
  5. BZOJ1492:[NOI2007]货币兑换——题解
  6. Hive架构及应用介绍【链接】
  7. MyBatis子查询
  8. eclipse的最新版本luna的中建立svn和maven
  9. Leetcode 380. 常数时间插入、删除和获取随机元素
  10. 人工智能----TensorFlow开篇简介