句柄类的应用以减少重复编译

来源:互联网 发布:淘宝手机收藏地址转换 编辑:程序博客网 时间:2024/06/13 14:58

//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() {     …………………………………………………………………………<p style="COLOR: red; FONT-SIZE: 16px"><strong>具体请点击:<a target=_blank href="http://www.verydemo.com/demo_c101_i26628.html" target="_blank">http://www.verydemo.com/demo_c101_i26628.html</a></strong></p>
0 0
原创粉丝点击