gpt4 book ai didi

c++ - C++ 中的类/函数顺序重要吗?

转载 作者:可可西里 更新时间:2023-11-01 15:35:36 27 4
gpt4 key购买 nike

我开始学习 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++ 中的类/函数顺序是否重要?我以为没有。请澄清问题。

最佳答案

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

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

请注意,在您的情况下,您可以这样做。 ( 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++ - C++ 中的类/函数顺序重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26122024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com