gpt4 book ai didi

forward-declaration - 前向声明和前向引用有什么区别?

转载 作者:行者123 更新时间:2023-12-04 00:02:56 35 4
gpt4 key购买 nike

前向声明和前向引用有什么区别?
在我看来,前向声明是当你声明一个尚未实现的函数时,但这不正确吗?您是否必须查看特定情况以声明案例“前向引用”或“前向声明”?

最佳答案

一个 前向声明是在实现和使用方法或变量之前的声明。前向声明的目的是节省编译时间。

变量的前向声明会留出存储空间,因此您可以稍后设置该变量的值。

函数的前向声明也称为“函数原型(prototype)”,是一种声明语句,它告诉编译器函数的返回类型是什么,函数的名称是什么,以及它的参数类型。 C/C++ 和 Pascal 等语言的编译器将声明的符号(包括函数)存储在查找表中,并在代码中遇到它们时引用它们。这些编译器按顺序读取您的代码,即从上到下,因此如果您不前向声明,编译器会在查找表中发现它无法引用的符号,并引发它不知道的错误如何响应函数。

前向声明是对您在别处定义(填写实现)函数的编译器的提示。

例如:

int first(int x); // forward declaration of first

...

int first(int x) {
if (x == 0) return 1;
else return 2;
}

但是,你会问,为什么我们不让编译器对每个源文件进行两次传递:第一次对里面的所有符号进行索引,第二次解析引用并查找它们?根据丹故事:

When C was created in 1972, computing resources were much more scarce and at a high premium -- the memory required to store a complex program's entire symbolic table at once simply wasn't available in most systems. Fixed storage was also expensive, and extremely slow, so ideas like virtual memory or storing parts of the symbolic table on disk simply wouldn't have allowed compilation in a reasonable timeframe... When you're dealing with magnetic tape where seek times were measured in seconds and read throughput was measured in bytes per second (not kilobytes or megabytes), that was pretty meaningful.

C++, while created almost 17 years later, was defined as a superset of C, and therefore had to use the same mechanism.

By the time Java rolled around in 1995, average computers had enough memory that holding a symbolic table, even for a complex project, was no longer a substantial burden. And Java wasn't designed to be backwards-compatible with C, so it had no need to adopt a legacy mechanism. C# was similarly unencumbered.

As a result, their designers chose to shift the burden of compartmentalizing symbolic declaration back off the programmer and put it on the computer again, since its cost in proportion to the total effort of compilation was minimal.



在 Java 和 C# 中,标识符会自动从源文件中识别并直接从动态库符号中读取。在这些语言中,出于同样的原因,不需要头文件。

一个 前向引用 是相反的。它是指在声明之前使用实体。例如:
int first(int x) {
if (x == 0) return 1;
return second(x-1); // forward reference to second
}

int second(int x) {
if (x == 0) return 0;
return first(x-1);
}

请注意,“前向引用”有时用作“前向声明”的同义词,但并不经常使用。

关于forward-declaration - 前向声明和前向引用有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/696562/

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