基于对象编程风格

本文通过两个示例介绍了如何使用C++中的函数适配器将一种接口转换为另一种接口,以及如何利用线程库进行多线程编程。第一个示例展示了如何使用std::bind将成员函数适配为接受不同参数类型的函数。第二个示例则演示了如何创建并启动线程。

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

函数适配器:将一种接口适配成另一种接口

#include<iostream>
#include<functional>
using namespace std;

class Foo{
public:
    void memberFunc(double d, int i, int j)
    {
        cout << d << endl;
        cout << i << endl;
        cout << j << endl;
    }
};

int main()
{
    Foo foo;
    using placeholders::_1;
    function<void (int)> fp = bind(&Foo::memberFunc, &foo, 0.5, _1, 10);
    fp(100);
    return 0;
}

编译:

g++ -g -std=c++11 bf_test.cpp -o bf_test
  • 例二
    Thread_test.cpp :
#include"Thread.h"
#include<unistd.h>
#include<iostream>
using namespace std;


void threadFunc()
{
    cout << "ThreadFunc..." << endl;
}

void threadFunc2(int count)
{
    while(count--){
        cout << "threadFunc2()..." << endl;
        sleep(1);
    }
}

int main()
{
    Thread t1(threadFunc);
    Thread t2(bind(threadFunc2, 3));
    t1.Start();
    t2.Start();
    t1.Join();
    t2.Join();
    return 0;
}

Thread.h :

#include"Thread.h"
#include<unistd.h>
#include<iostream>
using namespace std;


void threadFunc()
{
    cout << "ThreadFunc..." << endl;
}

void threadFunc2(int count)
{
    while(count--){
        cout << "threadFunc2()..." << endl;
        sleep(1);
    }
}

int main()
{
    Thread t1(threadFunc);
    Thread t2(bind(threadFunc2, 3));
    t1.Start();
    t2.Start();
    t1.Join();
    t2.Join();
    return 0;
}

Thread.cpp :

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

Thread::Thread(const ThreadFunc& func):func_(func)
{
    cout << "create Thread..." << endl;
}


void Thread::Start()
{
    pthread_create(&threadId_t, NULL, ThreadRoutine, this);
}


void* Thread::ThreadRoutine(void* arg)
{
    //静态成员函数无法直接调用非静态成员函数(没有this指针)    
    Thread* thread = static_cast<Thread*>(arg);
    thread->Run();
    return NULL;
}

void Thread::Join()
{
    pthread_join(threadId_t, NULL);
}

//需要自己实现
void Thread::Run()
{
    func_();
}

Thread.h :

#ifndef _THREAD_H_
#define _THREAD_H_

#include<pthread.h>
#include<functional>
class Thread{
public:
    typedef std::function<void()> ThreadFunc;
    explicit Thread(const ThreadFunc& func);


    void Start();
    void Join();

private:
    static void* ThreadRoutine(void* arg);

    void Run();
    ThreadFunc func_;
    pthread_t threadId_t;

};

#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值