C++缺省参数、bind

目录

1,全部缺省

2,部分缺省

3,bind

(1)普通函数,绑定常量

(2)普通函数,绑定变量

(3)类的成员函数,static

(4)类的成员函数,非static

(5)实用场景


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;
}

这个用法和仿函数还是有明显差别的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值