目录
1,全部缺省
2,部分缺省
3,bind
1,全部缺省
#include<iostream>
using namespace std;
int f(int x = 1, int y = 2)
{
return x + y;
}
int main()
{
cout << f() << " " << f(3) << " " << f(4, 5);
return 0;
}
输出:3 5 9
参数从左往右赋值,所以f(3)是第一个参数x=3
#include<iostream>
using namespace std;
double f(int x = 1, double y = 2)
{
return x + y;
}
int main()
{
cout << f(3.7);
return 0;
}
输出:5
参数仍然是从左往右赋值,可以隐式转换,不能转换就编译失败。
2,部分缺省
如果一部分参数有缺省值,一部分没有,那么必须是所有没有缺省值的都在有缺省值的参数的左边。
#include<iostream>
using namespace std;
double f(int x , double y=2 )
{
return x + y;
}
int main()
{
cout << f(3.7);
return 0;
}
输出5
总之,无论是全部缺省还是部分缺省,传参的时候一定是从左往右依次赋值。
3,bind
bind的功能是根据一个已有的函数得到一个新函数,把其中一部分入参和变量或者常量绑定,剩下的作为新函数的入参
(1)普通函数,绑定常量
#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
int fsum(int a,int b)
{
return a+b;
}
int main()
{
auto g=bind(fsum,5,_1);
cout<<g(6);
return 0;
}
输出11
(2)普通函数,绑定变量
#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
int fsum(int a,int b)
{
return a+b;
}
int main()
{
int x=5;
auto g=bind(fsum,x,_1);
x=3;
cout<<g(6);
return 0;
}
输出11
也就是说,bind函数执行的时候就把绑定的变量的值取到了,后面变量再改值也不影响绑定后的新函数。
即使把原函数fsum改成引用传递,也是这样。
(3)类的成员函数,static
#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
class A{
public:
static int fsum(int &a,int b)
{
return a+b;
}
};
int main()
{
int x=5;
auto g=bind(A::fsum,x,_1);
cout<<g(6);
return 0;
}
(4)类的成员函数,非static
非static函数需要把函数和对象都传进去
#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
class A{
public:
int fsum(int &a,int b)
{
return a+b;
}
};
int main()
{
int x=5;
A a;
auto g=bind(&A::fsum,a,x,_1);
cout<<g(6);
return 0;
}
(5)实用场景
利用bind,可以用类中的函数得到函数指针
#include<iostream>
#include<functional>
#include <algorithm>
using namespace std;
using namespace std::placeholders;
class A{
public:
bool cmp(int &a,int b)
{
return a<b;
}
};
int main()
{
A a;
auto g=bind(&A::cmp,a,_1,_2);
int x[5]={3,4,1,5,2};
sort(x,x+5,g);
for(int i=0;i<5;i++)cout<<x[i];
return 0;
}
这个用法和仿函数javascript:void(0)还是有明显差别的。