如何设计类,可以使得文件间的编译依存关系降至最低

方法一:使用pimpl idiom(pointer to implementation)的类,常被称为 Handle classes.
将类分割为两个类,一个只提供接口,另一个负责实现该接口。分离的关键在于以“声明的依存性”替换“定义的依存性”。

以Person类为例,假设负责实现的那个所谓implementation class取名为PersonImpl, Person将定义如下:

#include<string>    //标准程序库使用预编译头文件。
#include<memory>    //为了智能指针tr1::shared_ptr而含入

class PersonImpl;   //Person实现类的前置声明
class Date;         //Person接口用到的class的前置声明
class Address;

class Person{
public:
	Person(const std::string& name,const Date& birtthday,const Address& addr);
	std::string name() const;
	std::string birthDate() const;
	std::string address() const;
private:
	std::tr1::shared_ptr<PersonImpl> pImpl; //指针,指向实现物;
}
这里Person类中只内含一个指针成员,指向其实现类。这种设计常被称为pimpl idiom(指针实现)。
这样的设计下,Person的客户就完全与Date,Address以及PersonImpl分离了。这些类的任何修改都不需要Person客户端重新编译。
<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值