在这一环节,有人提到下列事项:

add.cpp:

int add(int x, int y)
{
    return x + y;
}

main.cpp:

#include <iostream>
 
int add(int x, int y); // forward declaration using function prototype
 
int main()
{
    using namespace std;
    cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
    return 0;
}

我们使用了前向声明,以便编译器在编译main.cpp时知道“add”是什么。如前所述,为您想要使用的位于另一个文件中的每个函数编写前向声明很快就会变得乏味。

你能进一步解释一下“前向申报”吗?如果我们在主函数中使用它会有什么问题?


当前回答

在c++中,术语“前向声明”主要用于类声明。请参阅后面的答案,了解为什么类的“前向声明”实际上只是一个简单的类声明,有一个花哨的名字。

换句话说,“forward”只是给这个术语增加了压载物,因为任何声明都可以被视为forward,只要它在使用之前声明了一些标识符。

(至于什么是声明而不是定义,请参见定义和声明之间的区别是什么?)

其他回答

int add(int x, int y); // forward declaration using function prototype

你能解释一下“前向声明”吗? 更多的进一步的吗?如果有什么问题 我们在main()函数中使用它?

它与#include"add.h"相同。如果你知道,预处理器会展开你在#include中提到的文件,在你写#include指令的。cpp文件中。这意味着,如果你写#include"add.h",你会得到同样的东西,就好像你在做"前向声明"。

我假设add.h有这一行:

int add(int x, int y); 

在c++中,术语“前向声明”主要用于类声明。请参阅后面的答案,了解为什么类的“前向声明”实际上只是一个简单的类声明,有一个花哨的名字。

换句话说,“forward”只是给这个术语增加了压载物,因为任何声明都可以被视为forward,只要它在使用之前声明了一些标识符。

(至于什么是声明而不是定义,请参见定义和声明之间的区别是什么?)

当编译器看到add(3,4)时,它需要知道这意味着什么。通过forward声明,你基本上告诉编译器add是一个接受两个int型并返回一个int型的函数。这对编译器来说是很重要的信息,因为它需要将正确表示形式的4和5放到堆栈中,并且需要知道add返回的东西是什么类型。

那时,编译器并不担心add的实际实现,即它在哪里(或者是否有一个)以及它是否编译。稍后,在调用链接器时编译源文件之后,就会看到它。

One problem is, that the compiler does not know, which kind of value is delivered by your function; is assumes, that the function returns an int in this case, but this can be as correct as it can be wrong. Another problem is, that the compiler does not know, which kind of arguments your function expects, and cannot warn you, if you are passing values of the wrong kind. There are special "promotion" rules, which apply when passing, say floating point values to an undeclared function (the compiler has to widen them to type double), which is often not, what the function actually expects, leading to hard to find bugs at run-time.

一个简短的补充:通常你把这些转发引用放在一个头文件中,属于实现函数/变量等的。c(pp)文件。在你的例子中,它看起来像这样: add.h:

extern int add(int a, int b);

关键字extern表示函数实际上是在外部文件中声明的(也可以是库等)。 你的main.c应该是这样的:

#include 
#include "add.h"

int main()
{
.
.
.