前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则SF.5: .cpp文件必须包含定义它接口的.h文件

C++核心准则SF.5: .cpp文件必须包含定义它接口的.h文件

作者头像
面向对象思考
发布2020-10-10 10:13:06
5370
发布2020-10-10 10:13:06
举报
文章被收录于专栏:C++核心准则原文翻译

SF.5: A .cpp file must include the .h file(s) that defines its interface

SF.5: .cpp文件必须包含定义它接口的.h文件

Reason(原因)

This enables the compiler to do an early consistency check.

这样可以让编译器尽早进行一致性检查。

Example, bad(反面示例)

代码语言:javascript
复制
// foo.h:
void foo(int);
int bar(long);SF.5: .cpp文件必须包含定义它接口的.h文件
int foobar(int);

// foo.cpp:
void foo(int) { /* ... */ }
int bar(double) { /* ... */ }
double foobar(int);

The errors will not be caught until link time for a program calling bar or foobar.

如果有程序调用bar或foobar,直到链接时这个错误才能被发现。

Example(示例)

代码语言:javascript
复制
// foo.h:
void foo(int);
int bar(long);
int foobar(int);

// foo.cpp:
#include <foo.h>

void foo(int) { /* ... */ }
int bar(double) { /* ... */ }
double foobar(int);   // error: wrong return type

The return-type error for foobar is now caught immediately when foo.cpp is compiled. The argument-type error for bar cannot be caught until link time because of the possibility of overloading, but systematic use of .h files increases the likelihood that it is caught earlier by the programmer.

当foo.cpp被编译时,foobar的返回值类型错误可以立即被发现。由于可能存在的重载,直到链接时,bar的参数类型错误才能被发现。但是系统性地使用.h文件会提高错误被程序员早期发现的可能性。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf5-a-cpp-file-must-include-the-h-files-that-defines-its-interface

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

本文分享自 面向对象思考 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档