首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >经验31:最小化文件之间编译依赖

经验31:最小化文件之间编译依赖

作者头像
AI老马
发布2026-01-13 14:51:42
发布2026-01-13 14:51:42
370
举报
文章被收录于专栏:AI前沿技术AI前沿技术

摘要:将定义和声明分开,并包含声明定义变量。使用句柄类和接口类减少文件依赖。

1,级联编译依赖

(cascading compilation dependencies)

代码语言:javascript
复制
class Person {
public:
Person(const std::string& name, const Date& birthday,const Address& addr);
    std::string name() const;
    std::string birthDate() const;
    std::string address() const;
    ...
private:
    std::string theName;    // implementation detail
    Date theBirthDate;      // implementation detail
    Address theAddress;     // implementation detail
};

如果正常的编译Person 需要知道相应类型的定义,需要包含特定的头文件

代码语言:javascript
复制
#include <string>
#include "date.h"
#include "address.h"

其主要的目的是,需要确切的知道在Person中相应 string ,date 和 address 类的大小。

最小化编译依赖的本质是:头文件编译时是自满足的,如果不能,那依赖声明而不是定义。

  • 避免使用对象,当引用和指针可以使用时。
  • 依赖于类的声明而不是类的定义。
  • 将声明和定义分离成两个文件
2,句柄类

句柄类主要的作用是,减少文件之间的依赖。

代码语言:javascript
复制
#include "Person.h" 
// we're implementing the Person class,
// so we must #include its class definition
#include "PersonImpl.h" 
// we must also #include PersonImpl's class
// definition, otherwise we couldn't call
// its member functions; note that
// PersonImpl has exactly the same
// member functions as Person — their
// interfaces are identical
Person::Person(const std::string& name, const Date& birthday,
                const Address& addr) : pImpl(new PersonImpl(name, birthday, addr)){}
std::string Person::name() const{
return pImpl->name();
}
3,接口类

使用虚拟类实现

代码语言:javascript
复制
class Person {
public:
virtual ~Person();
virtual std::string name() const = 0;
virtual std::string birthDate() const = 0;
virtual std::string address() const = 0;
...
};

具体的使用方式是:

代码语言:javascript
复制
class Person {
public:
    ...
    static std::tr1::shared_ptr<Person>     // return a tr1::shared_ptr to a new
    create(const std::string& name,         // Person initialized with the
    const Date& birthday,                   // given params; see Item 18 for
    const Address& addr);                   // why a tr1::shared_ptr is returned
    ...
};

客户端使用

代码语言:javascript
复制
std::string name;
Date dateOfBirth;
Address address;
...
// create an object supporting the Person interface
std::tr1::shared_ptr<Person> pp(Person::create(name, dateOfBirth, address));
...
std::cout << pp->name() // use the object via the
<< " was born on " // Person interface
<< pp->birthDate()
<< " and now lives at "
<< pp->address();
... // the object is automatically deleted when pp goes out of scope

总结:

1)将声明和实现分开,并成对改变。

2)使用句柄类和接口类,减少依赖。即仅当声明类的接口改变时,才会重新编译。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-02-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AI老马啊 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1,级联编译依赖
  • 2,句柄类
  • 3,接口类
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档