将声明和定义分离为C ++中的优点和缺点是什么? [英] What are the advantages and disadvantages of separating declaration and definition as in C++?

查看:263
本文介绍了将声明和定义分离为C ++中的优点和缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,函数,变量和常量的声明和定义可以这样分隔:

In C++, declaration and definition of functions, variables and constants can be separated like so:

function someFunc();

function someFunc()
{
  //Implementation.
}

事实上,在类的定义中,通常是这样。类通常使用它的成员在.h文件中声明,然后在相应的.C文件中定义它们。

In fact, in the definition of classes, this is often the case. A class is usually declared with it's members in a .h file, and these are then defined in a corresponding .C file.

这种方法的缺点?

推荐答案

历史上这是帮助编译器。你必须在使用它们之前给它一个名字列表 - 无论这是真正的用法,还是一个向前声明(C的默认函数原型)。

Historically this was to help the compiler. You had to give it the list of names before it used them - whether this was the actual usage, or a forward declaration (C's default funcion prototype aside).

现代编译器对于现代语言表明,这不再是必要的,所以C& C ++的(以及Objective-C,和可能的其他)语法这里是组织的行李。事实上,这是C ++的一个大问题,即使添加一个合适的模块系统也无法解决。

Modern compilers for modern languages show that this is no longer a necessity, so C & C++'s (as well as Objective-C, and probably others) syntax here is histotical baggage. In fact one this is one of the big problems with C++ that even the addition of a proper module system will not solve.

缺点是:大量的嵌套包含文件我已经跟踪包括树之前,他们是令人惊讶的巨大)和声明和定义之间的冗余 - 所有导致更长的编码时间和更长的编译时间(比较可比较的C ++和C#项目之间的编译时间这是这样的原因之一区别)。必须为您提供的任何组件的用户提供头文件。 ODR违规的机会。依赖预处理器(许多现代语言不需要预处理器步骤),这使得你的代码更加脆弱,工具更难解析。

Disadvantages are: lots of heavily nested include files (I've traced include trees before, they are surprisingly huge) and redundancy between declaration and definition - all leading to longer coding times and longer compile times (ever compared the compile times between comparable C++ and C# projects? This is one of the reasons for the difference). Header files must be provided for users of any components you provide. Chances of ODR violations. Reliance on the pre-processor (many modern languages do not need a pre-processor step), which makes your code more fragile and harder for tools to parse.

优点:不多。你可以认为你得到一个函数名列表集合在一起的一个地方为文档目的 - 但大多数IDEs有一些类型的代码折叠能力,这些天,任何大小的项目应该使用doc生成器(如doxygen)无论如何。有了一个更清洁,无处理器,基于模块的语法,工具更容易遵循你的代码,并提供这个和更多,所以我认为这个优势只是关于模糊。

Advantages: no much. You could argue that you get a list of function names grouped together in one place for documentation purposes - but most IDEs have some sort of code folding ability these days, and projects of any size should be using doc generators (such as doxygen) anyway. With a cleaner, pre-processor-less, module based syntax it is easier for tools to follow your code and provide this and more, so I think this "advantage" is just about moot.

这篇关于将声明和定义分离为C ++中的优点和缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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