类/函数的顺序在C++中重要吗

Does class/function order matter in C++?

本文关键字:C++ 函数 顺序      更新时间:2023-10-16

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

#include <iostream>
using namespace std;
struct A {};
struct B {
    A a;
}
void hi() {
    cout << "hi" << endl;
}
int main() {
    hi();
    return 0;
}

但事实并非如此:

struct B {
    A a;
}
struct A {};
int main() {
    hi();
    return 0;
}
void hi() {
    cout << "hi" << endl;
}

它给了我错误:

error: 'A' does not name a type
error: 'hi' was not declared in this scope

类/函数的顺序在C++中是否重要?我以为没有。请澄清这个问题。

是的,在使用/调用类/函数之前,您必须至少声明,即使实际定义直到之后才出现。

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

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

void hi();    // This function is now declared
struct A; // This type is now declared
struct B {
    A* a; // we can now have a pointer to it
};
int main() {
    hi();
    return 0;
}
void hi() {    // Even though the definition is afterwards
    cout << "hi" << endl;
}
struct A {}; // now A has a definition