有效降低编译依存关系
接口类:不负责实现,内含一个实现类对象的指针或引用,通过这个指针或引用实现
class WidgetImpl; //forwarding declararion, reduce coupling, accelerate compilation
class Widget //interface, for users
{
public:
std::size_t getHeight();
...
private:
WidgetImpl* pImpl;
}
std::size_t Widget::getHeight()
{
return pImpl->getHeight();
}
实现类:负责实现。实现类内部结构的更改不影响接口类,耦合度低
class WidgetImpl //actualization, changes inside dose not influence interface for users
{
public:
std::size_t getHeight();
...
private:
size_t height;
}
std::size_t WidgetImpl::getHeight()
{
return height;
}
可以解决头文件互相包含的问题,其中一个#include
,另外一个使用前置声明,如下
//a.h
class B; //forwarding declaration
class A
{
public:
...
private:
B* b; //or B& b
}
//b.h
#include "a.h"
class B
{
public:
...
private:
A* a; //or A a; or A& a
}