为什么有头文件和 .cpp 文件? [英] Why have header files and .cpp files?

查看:44
本文介绍了为什么有头文件和 .cpp 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 C++ 有头文件和 .cpp 文件?

Why does C++ have header files and .cpp files?

推荐答案

嗯,主要原因是将接口与实现分离.头文件声明了一个类(或正在实现的任何东西)将做什么,而 cpp 文件定义了它将如何"执行这些功能.

Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.

这减少了依赖关系,因此使用标头的代码不一定需要知道实现的所有细节以及仅需要的任何其他类/标头.这将减少编译时间以及实现中的某些内容发生变化时所需的重新编译量.

This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.

它并不完美,您通常会求助于Pimpl Idiom 之类的技术 正确分离接口和实现,但这是一个好的开始.

It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.

这篇关于为什么有头文件和 .cpp 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆