首页 文章详情

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

面向对象思考 | 306 2020-10-08 03:30 0 0 0
UniSMS (合一短信)

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(反面示例)

// 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(示例)

// foo.h:
void foo(int);
int bar(long);
int foobar(int);

// foo.cpp:
#include

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


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter