在C ++中函数顺序是否重要? [英] Does function order matter in C++?

查看:108
本文介绍了在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;
}

这篇关于在C ++中函数顺序是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆