c++ - 为什么即使没有任何类声明也需要原型(prototype)?

标签 c++ function-prototypes

如果我这样做: 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/

相关文章:

c++ - 编译器如何选择正确的重载函数?

c - 为什么我的用户定义数组的平均值不正确? C

c - 编译C程序时“Function prototypes are an ANSI feature”错误

c++ - 如何编写 Qt HTTP GET 请求?

c++ - C/C++ 位数组或位 vector

c - 将函数指针转换为 void 有什么影响?

c++ - 错误 : prototype for ‘XXX’ does not match any in class ‘YYY’

c++ - 如何声明模板化函数以便可以在类构造函数/函数中传递

c++ - fstream,先写,再读,再写,最后一次写失败,不知道是什么原因

c++ - 加载共享库时出错 : libgsl. so.0:无法打开共享对象文件:没有这样的文件或目录