在C ++中函数顺序是否重要?

问题描述:

我开始学习C ++。在IDE代码块中,编译:

I'm beginning to learn C++. In the IDE codeblocks, this compiles:

#include <iostream>
using namespace std;

void hi() {
    cout << "hi" << endl;
}

int main() {
    hi();
    return 0;
}

但这不会:

int main() {
    hi();
    return 0;
}

void hi() {
    cout << "hi" << endl;
}

它给我的错误:

错误:'hi'未在此范围内声明

?我以为没有。请澄清问题。

Should function order matter in C++? I thought it doesn't. Please clarify the issue.

是的,您必须至少声明

这就是为什么你经常在头文件中声明函数,然后 #include 他们在你的cpp文件的顶部。然后你可以使用任何顺序的函数,因为他们已经被有效地声明。

That is why you often declare the functions in header files, then #include them at the top of your cpp file. Then you can use the functions in any order, since they have already been effectively declared.

注意,在你的情况下,你可以这样做。 (工作示例

Note in your case you could have done this. (working example)

void hi();    // This function is now declared

int main() {
    hi();
    return 0;
}

void hi() {    // Even though the definition is afterwards
    cout << "hi" << endl;
}