为什么我们不能在 C 中调用函数?在声明之前但是我们可以在Java中做到这一点吗?
C++ 程序:
#include<iostream>
int main(){
sayHello();
}
void sayHello(){
std::cout << "Hello\n";
}
输出:
main.cpp: In function 'int main()':
main.cpp:4:5: error: 'sayHello' was not declared in this scope
sayHello();
^~~~~~~~
Java 程序:
public class Main
{
public static void main(String[] args) {
sayHello();
}
public static void sayHello(){
System.out.println("Hello");
}
}
输出:
Hello
是否只是因为 Java 提供了在编译过程中解决函数之间依赖关系的支持,而 C++ 则没有。如果是,C++ 没有提供此功能是否有具体原因?
C++ Program:
#include<iostream>
int main(){
sayHello();
}
void sayHello(){
std::cout << "Hello\n";
}
Output:
main.cpp: In function 'int main()':
main.cpp:4:5: error: 'sayHello' was not declared in this scope
sayHello();
^~~~~~~~
Java Program:
public class Main
{
public static void main(String[] args) {
sayHello();
}
public static void sayHello(){
System.out.println("Hello");
}
}
Output:
Hello
Is it just because Java provides support to resolve any dependencies among functions during compilation but C++ does not. If yes, Is there a specific reason that C++ did not provide this feature?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上面代码的区别在于,在 C++ 中,有两个方法,并且 main 方法在 sayHello() 方法之前运行,因为编译器不知道 sayHello 存在。
而在 Java 中,您有一个包含这些方法的类。因此,当您运行代码时,会创建一个类,编译器知道该类的所有方法,然后当运行 main 方法时,它就能够执行 sayHello() 方法。
我希望它能澄清你的问题。
the difference in the code above is that in C++ you have two methods and main method is run before the sayHello() method due to which compiler does not know that sayHello exists.
Whereas in Java you have a class which contains those methods. So when you run the code the class is created along which all the methods are known to the compiler, then when main method is run it is able to execute sayHello() method.
I hope it clarifies your question.
这是因为代码只有在声明后才可用。
在 C++ 示例中,您可以在定义
main()
之前声明sayHello()
,如下所示:Java 的不同之处在于每个文件都包含一个类。定义类时,首先声明所有类成员,然后才考虑它们的定义。因此,在您的 Java 示例中,第一个类
Main
是使用方法main(String[])
和sayHello()
定义的,然后才定义它main
方法调用已声明的sayHello
。您可以通过像在 Java 中一样创建类来在 C++ 中复制此行为:This is because code becomes available only after its declaration.
In your C++ example, you could declare
sayHello()
before definingmain()
like this:What's different about Java is that every file contains a class. When a class is defined, first all of the class members are declared, and only then their definition is considered. So in your Java example, first class
Main
is defined with methodsmain(String[])
andsayHello()
, and only then it's defined that themain
method callssayHello
that is already declared. You can replicate this behaviour in C++ by creating a class like in Java: