句柄类的应用中减少重复编译的方法

来源:岁月联盟 编辑:猪蛋儿 时间:2011-11-17

 

我们知道,当一个源文件所依赖的头文件被修改时,这个源文件需要被重新编译(易碎的基类问题),为了能讲述我将说明的这个方法,我们先来看看一个简单的例子,其代码如下:

view plain

//head.h 

struct A 

{ int i;}; 

 

class B 

    A* a; 

public: 

    B(int n = 0); 

    void show(); 

    ~B(); 

}; 

 

//head.cpp 

#include "head.h" 

#include <iostream.h> 

B::B(int n) 

    a = new A; 

    a->i = n; 

void B::show() 

    cout << a->i; 

B::~B() 

    delete a; 

 

//main.cpp 

#include <iostream> 

#include "head.h" 

using namespace std; 

int main() 

    B b(1); 

    b.show(); 

    return 1; 

如果我们要修改结构体A,比如我们需要对A添加一个成员变量,这时候head.h改变了,从而包含了它的head.cpp和main.cpp都需要重新编译

我们知道类B是一个包装了类A的句柄类,对于这种形式,如何修改代码使得修改A的定义时能减少重新编译呢?

观察head.h,我们发现在B的申明过程中并不需要完全定义类A,利用这点我们可以稍微修改下代码,修改后的代码如下:

 

//head.h 

class B 

    struct A;//不完整的类类型说明 

    A* a; 

public: 

    B(int n = 0); 

    void show(); 

    ~B(); 

}; 

 

//head.cpp 

#include "head.h" 

#include <iostream.h> 

struct B::A //A的完全定义 

    int i; 

}; 

B::B(int n) 

    a = new A; 

    a->i = n; 

void B::show() 

    cout << a->i; 

B::~B() 

    delete a; 

 

//main.cpp 

#include <iostream> 

#include "head.h" 

using namespace std; 

int main() 

    B b(1); 

    b.show(); 

    return 1; 

这样修改后,如果我们需要修改A的定义,我们只需要修改head.cpp,从而可以避免main.cpp需要重新定义

 

总结:如果我们的系统中存在有句柄类,并且系统非常大,则我们可能需要这种所谓的奇技淫巧来避免编译时间过多

作者 yucan1001

图片内容