【问题标题】:Where should function prototypes be declared?函数原型应该在哪里声明?
【发布时间】:2014-10-24 03:59:48
【问题描述】:

原型应该在哪里声明?例如在 include 语句之后,还是在 main 方法之前?我知道它们都可以编译,但被认为更标准或更可修改?

#include <iostream>
#include <cstdlib>

const unsigned int PI = 3.14;

using namespace std;

int myFunc(int x, int y);
long factorial(int n);

int main()
{
  //...
  return 0;
}

#include <iostream>
#include <cstdlib>

int myFunc(int x, int y);
long factorial(int n);

using namespace std;



int main()
{
  //...
  return 0;
}

或者根本不应该使用它们并且应该最后声明 main?

如果一种方式更易读或更受欢迎,没有人真正解决过。

【问题讨论】:

  • 在您的示例中,它没有任何区别。在实际调用函数之前的某个地方。
  • 你的两个程序没有任何区别。无论如何,你不应该使用using namespace std
  • 我建议将它们放在标题中,并在该翻译单元中进行主要独奏。

标签: c++ readability function-prototypes


【解决方案1】:

只有在你的函数原型中实际使用了std 中的类型才有意义。在你的例子中你没有,所以在你的情况下并不重要。

这不会编译:

#include <string>

void foo(string const & s);

using namespace std;

但这会:

#include <string>

using namespace std;

void foo(string const & s);

但无论如何you shouldn't use using namespace std

【讨论】:

    【解决方案2】:

    函数原型必须在函数使用之前声明。它甚至可以在块范围内声明。

    【讨论】:

      【解决方案3】:

      在您展示的示例中,这无关紧要。

      规则是:

      一个函数必须在使用之前声明(在这种情况下:调用它)。

      注意:如果函数是在使用之前定义的,那么你不需要显式的函数声明。函数定义服务于目的。

      【讨论】: