为什么即使没有任何类声明也需要原型? [英] Why prototype is required even without any class declaration?

查看:109
本文介绍了为什么即使没有任何类声明也需要原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只是这样做:
Ex1:

#include <iostream>

int main()
{
    //try to call doSomething function
    doSomething();
}

void doSomething()
{
    std::cout << "Call me now!" << std::endl;
}

我得到编译错误!因为编译不知道是什么是doSomething。

I get compilation error! Because the compile doesn´t know what is "doSomething".

但是如果我改变doSomething的位置在第一位,程序编译成功。
Ex2:

But if I change the position of doSomething to come in first place, the program compiles successfully. Ex2:

#include <iostream>

void doSomething()
{
    std::cout << "Call me now!" << std::endl;
}

int main()
{
    //try to call doSomething function
    doSomething();
}



我可以声明原型如下:
Ex3:

#include <iostream>

void doSomething(void);

int main()
{
    //try to call doSomething function
    doSomething();
}

void doSomething()
{
    std::cout << "Call me now!" << std::endl;
}

但是为什么第一个例子不工作?为什么我甚至必须声明一个原型或最后调用函数和主函数?

But why the first example does not work? Why I even have to declare a prototype or call functions first and main function at last?

谢谢!

推荐答案

如果编译器没有看到定义或声明,就不能调用函数,首先是简单的。原型或实际定义必须出现在调用之前。

You can't call a function without the compiler having seen either the definition or a declaration, first -- simple as that. A prototype or the actual definition must appear before a call.

这篇关于为什么即使没有任何类声明也需要原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆