简体   繁体   English

程序顶部的声明与定义(最佳实践)

[英]Declarations vs. Definitions at the top of your program (Best Practice)

Using a function declaration at the top of your function, then later defining it under main seems a bit redundant.在 function 的顶部使用 function 声明,然后在 main 下定义它似乎有点多余。 Considering the practices of DRY, is standard practice in the C++ community to simply declare the function fully at the top (or even just define in a seperate functions.cpp file, with declarations in the header.hpp file), rather than declare then later define? Considering the practices of DRY, is standard practice in the C++ community to simply declare the function fully at the top (or even just define in a seperate functions.cpp file, with declarations in the header.hpp file), rather than declare then later定义?

I realize that all ways would produce the same result, but I would like to hone in on my formatting skills, and eliminate redundancy.我意识到所有方法都会产生相同的结果,但我想磨练我的格式化技巧,并消除冗余。 Why declare then later define as opposed to just defining at the top before main?为什么先声明然后再定义,而不是在 main 之前的顶部定义? Perhaps this is a tabs vs. spaces type of debate, but maybe thats all I need to know lol也许这是一个制表符与空格类型的辩论,但也许这就是我需要知道的一切,哈哈

Thanks!谢谢!

There are cases where you have no choice other than first providing a declaration and then the definition.在某些情况下,您别无选择,只能先提供声明,然后再提供定义。 For example when there is mutual dependency:例如当存在相互依赖时:

int bar(int x);

int foo(int x) {
    if (x == 1) return bar(x);
    return x;
}
int bar(int x) {
    if (x==0) return foo(x);
    return x;
}

Seperating declaration and definition is not considered a violation of DRY or as redundant.将声明和定义分开被视为违反 DRY 或多余。 Probably the most common is to have declarations in headers and definitions in source files.最常见的可能是在源文件的头文件和定义中声明。

There may be some cases that you have to provide function signature in advance, and its implementation only later at some point.在某些情况下,您可能必须提前提供 function 签名,并且仅在稍后的某个时间点实现。 The best example is the cyclic dependency of functions, so one needs to be defined before the other one, making a closed loop.最好的例子是函数的循环依赖,因此需要在另一个之前定义一个,形成一个闭环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM