问题描述
我开始学习C ++。在IDE代码块中,它会编译:
I'm beginning to learn C++. In the IDE codeblocks, this compiles:
#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 ++中类/函数的顺序应该重要吗?我以为不是。请澄清问题。
Should class/function order matter in C++? I thought it doesn't. Please clarify the issue.
推荐答案
是的,您必须至少声明类/函数,然后才能进行使用/调用它,即使之后才真正定义。
Yes, you must at least declare the class/function before you use/call it, even if the actual definition does not come until afterwards.
这就是为什么您经常在头文件中声明类/函数,然后在<$ c $中声明c> #include 放在cpp文件顶部。然后,您可以按任何顺序使用类/函数,因为它们已经被有效地声明了。
That is why you often declare the classes/functions in header files, then #include
them at the top of your cpp file. Then you can use the classes/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
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
这篇关于类/函数顺序在C ++中重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!