面向对象编程和基于对象编程
面向对象编程:面向对象也就是把对象作为“接口”暴露出去,一般内部是一个 接口 或者抽象类。Thread.h123456789101112131415161718192021222324252627282930313233#ifndef _THREAD_H_#define _THREAD_H_#include <pthread.h>class Thread{public :Thread();virtual ~Thread();void Start();void Join();private :// 纯虚函数 ²»ÐҪvoid Run() =0 ;pthread_t threadId_ ;};#ifndef _THREAD_H_#define _THREAD_H_#include <pthread.h>class Thread{public :Thread();virtual ~Thread();void Start();void Join();private :// 纯虚函数 ²»ÐҪvoid Run() =0 ;pthread_t threadId_ ;};Thread.cpp1234567891011121314151617181920212223242526272829303132333435363738#include "Thread.h"#include <iostream>using namespace std;Thread::Thread() : autoDelete_(false){cout<<"Thread ..."<<endl;}Thread::~Thread(){cout<<"~Thread ..."<<endl;}void Thread::Start(){pthread_create(&threadId_, NULL, ThreadRoutine, this);}void Thread::Join(){pthread_join(threadId_, NULL);}void* Thread::ThreadRoutine(void* arg){Thread* thread = static_cast<Thread*>(arg);thread->Run();if (thread->autoDelete_)delete thread;return NULL;}void Thread::SetAutoDelete(bool autoDelete){autoDelete_ = autoDelete;}Thread_test.cpp1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#include "Thread.h"#include <unistd.h>#include <iostream>using namespace std;class TestThread : public Thread{public:TestThread(int count) : count_(count){cout<<"TestThread ..."<<endl;}~TestThread(){cout<<"~TestThread ..."<<endl;}private:void Run(){while (count_--){cout<<"this is a test ..."<<endl;sleep(1);}}int count_;};int main(void){/*TestThread t(5);t.Start();t.Join();*/TestThread* t2 = new TestThread(5);t2->SetAutoDelete(true);t2->Start();t2->Join();for (; ; )pause();return 0;}基于对象编程:基于对象编程,提供出来的就不是“接口”了, 而是一个具体的类,虽然他和面向对象想一个都是起到回调的作用,但是他的回调不是通过继承来实现相应的虚函数,可以独立的函数,或者成员函数。看下面的例子就知道了。Thread.h1234567891011121314151617181920#ifndef _THREAD_#define _THREAD_#include <pthread.h>#include <boost/function.hpp>class Thread {public :typedef boost::function<void ()> ThreadFunc ;explicit Thread( const ThreadFunc &func) ;~Thread();void Start () ;void Join();void SetAutoDelete(bool autoDelete);private :static void* ThreadRoutine( void *arg) ;void Run();ThreadFunc func ;pthread_t threadId ;bool autoDelete_;} ;#endif // _THREAD_H_Thread.cpp123456789101112131415161718192021222324252627282930补充:综合编程 , 其他综合 ,
上一个:epoll 1
下一个:libRTMP使用说明