在这一环节,有人提到下列事项:
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”是什么。如前所述,为您想要使用的位于另一个文件中的每个函数编写前向声明很快就会变得乏味。
你能进一步解释一下“前向申报”吗?如果我们在主函数中使用它会有什么问题?
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.