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

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”是什么。如前所述,为您想要使用的位于另一个文件中的每个函数编写前向声明很快就会变得乏味。

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


当前回答

编译器查找在当前翻译单元中使用的每个符号是否先前声明在当前单元中。这只是一个样式问题,在源文件的开头提供所有方法签名,而稍后提供定义。它的重要用途是将一个类的指针用作另一个类的成员变量。

//foo.h
class bar;    // This is useful
class foo
{
    bar* obj; // Pointer or even a reference.
};

// foo.cpp
#include "bar.h"
#include "foo.h"

因此,尽可能在类中使用前向声明。如果您的程序只有函数(带有ho头文件),那么在开始时提供原型只是一个风格问题。如果头文件出现在一个只有函数头的普通程序中,那么无论如何都会出现这种情况。

其他回答

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

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

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

编译器查找在当前翻译单元中使用的每个符号是否先前声明在当前单元中。这只是一个样式问题,在源文件的开头提供所有方法签名,而稍后提供定义。它的重要用途是将一个类的指针用作另一个类的成员变量。

//foo.h
class bar;    // This is useful
class foo
{
    bar* obj; // Pointer or even a reference.
};

// foo.cpp
#include "bar.h"
#include "foo.h"

因此,尽可能在类中使用前向声明。如果您的程序只有函数(带有ho头文件),那么在开始时提供原型只是一个风格问题。如果头文件出现在一个只有函数头的普通程序中,那么无论如何都会出现这种情况。

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.

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(pp)文件。在你的例子中,它看起来像这样: add.h:

extern int add(int a, int b);

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

#include 
#include "add.h"

int main()
{
.
.
.