(轉貼) C++接口与实现分离的2种方法 (C/C++)
轉貼自http://www.cppblog.com/mzty/archive/2007/08/06/29441.html
方法一:使用另一个实现类分装类的私有成员和函数,这种方法称为Pimpl方法。
test.h
test.cpp
总结:
接口与实现的分离,有助于我们对代码实现的保护,特别是如果我们开发lib共别人使用使,更要注意。在实现分离的过程中,最好采用上面的第一种方法的智能指针boost::shared_ptr的实现,简单安全。
方法一:使用另一个实现类分装类的私有成员和函数,这种方法称为Pimpl方法。
test.h
#pragma once
#include "shared_ptr.hpp"
class CTest
{
public:
CTest(void);
~CTest(void);
void DoSomething();
private:
class CTestImp;
boost::shared_ptr<CTestImp> pimpl_;
};
#include "shared_ptr.hpp"
class CTest
{
public:
CTest(void);
~CTest(void);
void DoSomething();
private:
class CTestImp;
boost::shared_ptr<CTestImp> pimpl_;
};
test.cpp
#include "Test.h"
#include <iostream>
class CTest::CTestImp
{
private:
CTestImp(CTestImp const &){}
CTestImp & operator=(CTestImp const &){}
public:
CTestImp(){}
void DoSomething();
};
void CTest::CTestImp::DoSomething()
{
// do something.
std::cout<<"Imp class do something."<<std::endl;
}
CTest::CTest(void)
{
boost::shared_ptr<CTestImp> pImp(new CTestImp);
pimpl_ = pImp;
}
CTest::~CTest(void)
{
}
void CTest::DoSomething()
{
pimpl_->DoSomething();
}
#include <iostream>
class CTest::CTestImp
{
private:
CTestImp(CTestImp const &){}
CTestImp & operator=(CTestImp const &){}
public:
CTestImp(){}
void DoSomething();
};
void CTest::CTestImp::DoSomething()
{
// do something.
std::cout<<"Imp class do something."<<std::endl;
}
CTest::CTest(void)
{
boost::shared_ptr<CTestImp> pImp(new CTestImp);
pimpl_ = pImp;
}
CTest::~CTest(void)
{
}
void CTest::DoSomething()
{
pimpl_->DoSomething();
}
方法二:使用抽象类来实现接口与实现的分离。
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();
#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;
}
#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的实现,简单安全。