c++的header file+source file的分割有一个不干脆的地方:header file既是一个declaration,也是类数据结构的定义。如果是简单的c with class那没问题,因为struct的结构也是一种declaration。而到了c++,我们还需要封装,所以如果把内部struct暴露给别人就有问题了,抛开设计上的问题还有便以上的不方便:每次改了类的内部成员(增,删,改类型)后,但凡include过(直接或间接)这个头文件定义的其他地方也都要重新编译,在大项目中一不小心可能把半壁江山都重新编译了。我目前有2种方法来缓解这个问题。
假设一个简单的类定义和实现原版为:
//A.h
class A
{
public:
int API();
protected:
int mData;
}
//A.cpp
int A::API()
{
return mData + 1
}
第一种方法是Imp继承法:把A搞成一个虚接口类,再A.cpp里用一个AImp来继承A
//A.h
class A
{
public:
virtual void API();
}
//A.cpp
class AImp
{
public:
virtual int void API()
{
return mData +1;
}
protected:
int mData;
}
A* CreateA()
{
return new AImp();
}
Imp继承