bind 非静态成员函数时 注意传入对象

在使用STL中的bind进行非静态成员函数绑定时,需要注意每个非静态成员函数都隐含着对象指针作为第一个参数。这意味着在设置参数列表时,必须考虑这个隐含的对象参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;

std::function<int(void)> func;
int testFunc()
{
    cout << "global Func" << endl;
    return 0;
}
auto lambda = [](void) -> int {cout << "lambda func" << endl; return 0; };
class Func
{
    int operator()(void)
    {
        cout << "仿函数" << endl;
        return 0;
    }
};

class CFuntion
{
public:
    int ClassMember() { cout << "class member function" << endl; return 0; }
    int static StaticClassFunc() { cout << "static class member function" << endl; return 0; }
};
int main()
{
    func = testFunc;
    func();

    func = lambda;
    func();

    func = CFuntion::StaticClassFunc;
    func();

    CFuntion classFunc;
    func = std::bind(&CFuntion::ClassMember, classFunc); //bind非静态成员函数
    func();

    return 0;
}


#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

static int cnt = 0;

void f(const char *p)
{
    cout << ++cnt << ": ";
    cout << p << endl;
}

void f1(int i)
{
    cout<<i<<endl;
}

int main()
{
    vector<const char*> v;
    v.push_back("hello");
    v.push_back("world");
    //vector<const char*>::iterator it;
    for_each(v.begin(), v.end(), &f);
    vector<int> v1={1,2,3,4};
    for_each(v1.begin(),v1.end(),f1);
    return 0;
}

bind2nd在类的非静态成员函数使用的时候,要注意到每个非静态成员函数都隐含着this 指针,这也意味着在参数列表中的第一个参数始终是this

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

class AbstractDoor {
public:
    virtual void open(const char *str)const = 0;
    virtual ~AbstractDoor() { cout << "~AbstractDoor()" << endl; }
};

class HorizontalDoor :public AbstractDoor {
public:
    void open(const char *str)const 
    {
        cout << str << "HorizontalDoor" << endl;
    }
};

class VerticalDoor :public AbstractDoor {
public:
    void open(const char *str)const 
    {
        cout << str << "VerticalDoor" << endl;
    }
};

class DoorController {
protected:
    vector<AbstractDoor *> _doorVec;
public:
    void addDoor(AbstractDoor *door) {
        _doorVec.push_back(door);
    }
    void openDoor()const {
        for_each(_doorVec.begin(), _doorVec.end(), bind2nd(mem_fun(&AbstractDoor::open),"John: "));
    }
    ~DoorController() {
        for_each(_doorVec.begin(), _doorVec.end(), [](AbstractDoor *p) {
            delete p;
            p = nullptr;
        });
    }
};

int main()
{
    DoorController dc;
    dc.addDoor(new VerticalDoor());
    dc.addDoor(new HorizontalDoor);
    dc.addDoor(new VerticalDoor);
    dc.openDoor();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值