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

//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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值