方法一:使用另一個實作類別分裝類的私人成員和函數,這種方法稱為Pimpl方法。,也就是組合的方法。
#include <boost/shared_ptr.hpp>
#include <iostream>
class CTest
{
public:
CTest();
~CTest() {std::cout<<"CTest destructor!"<<std::endl;}
void do_something();
private:
class CTestImp;
boost::shared_ptr<CTestImp> pimpl_;
};
class CTest::CTestImp
{
public:
CTestImp(){std::cout<<"CTestImp constructor!"<<std::endl;}
~CTestImp(){std::cout<<"CTestImp destructor!"<<std::endl;}
void do_something();
private:
CTestImp(CTestImp const &){}
CTestImp & operator=(CTestImp const &){}
};
CTest::CTest(void)
{
boost::shared_ptr<CTestImp> pImp(new CTestImp);
pimpl_ = pImp;
}
void CTest::CTestImp::do_something()
{
std::cout<<"Imp class do something."<<std::endl;
}
void CTest::do_something()
{
pimpl_->do_something();
}
int main()
{
CTest test;
test.do_something();
return 0;
}
方法二:使用抽象類別來實現介面與實現的分離。
x.h
#pragma once
#include <stdio.h>
#include "shared_ptr.hpp"
using namespace boost;
class X
{
public:
virtual void f() = 0;
virtual void g() = 0;
protected:
~X() { printf("~X/n");}
};
shared_ptr<X> createX();
x.cpp
#include "X.h"
#include <stdio.h>
class X_impl: public X
{
private:
X_impl(){};
X_impl(X_impl const &);
X_impl & operator=(X_impl const &);
public:
~X_impl(){printf("~X_impl/n");};
virtual void f()
{
printf("X_impl.f()/n");
}
virtual void g()
{
printf("X_impl.g()/n");
}
private:
friend shared_ptr<X> createX();
};
shared_ptr<X> createX()
{
shared_ptr<X> px(new X_impl);
return px;
}
總結:
介面與實現的分離,有助於我們對代碼實現的保護,特別是如果我們開發lib共別人使用使,更要注意。在實現分離的過程中,最好採用上面的第一種方法的智能指標boost::shared_ptr的實現,簡單安全。