方法一:使用另一个实现类分装类的私有成员和函数,这种方法称为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的实现,简单安全。