如果我这样做: Ex1:
#include <iostream>
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
我收到编译错误!因为编译不知道什么是“doSomething”。
但如果我将 doSomething 的位置更改为第一位,程序将成功编译。 Ex2:
#include <iostream>
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
int main()
{
//try to call doSomething function
doSomething();
}
我可以这样声明原型(prototype): Ex3:
#include <iostream>
void doSomething(void);
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
但为什么第一个例子不起作用?为什么我什至必须先声明一个原型(prototype)或调用函数,最后调用 main 函数?
谢谢!
最佳答案
您不能在编译器没有首先看到定义或声明的情况下调用函数——就这么简单。原型(prototype)或实际定义必须出现在调用之前。
关于c++ - 为什么即使没有任何类声明也需要原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8199081/