函数原型-C ++ [英] Prototyping a function - C++

查看:115
本文介绍了函数原型-C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我的一些CPP教程使用了功能原型.我了解您必须初始化该函数,但是该函数的整体用途是什么?您能不能像在main()之前那样编写整个函数,而不是定义原型?

Lately, some of my CPP tutorials have used function prototypes . I understand you must initialize the function, but what is the overall use of it? Couldn't you use just as well write the entire function before main() instead of defining a prototype?

int returnValue(void);

int main()
{
  std::cout << returnValue() << std::endl;
  return 0;
}

int returnValue(void)
{
  return 10;
}

推荐答案

一个重要的用例是将实现与声明分开.换句话说,您可以在标头文件中声明函数/类等,然后在cpp文件中定义(即实现)它们.这样,您可以在共享或静态库中完全编译了实现的情况下分发程序.为了使用预编译的函数,您需要通过声明将其引入程序.示例:

One important usage case is when you separate your implementation from the declarations. In other words, you declare your functions/classes etc in a header file, and define (i.e. implement) them in cpp files. In this way, you can distribute your program with the implementation fully compiled in a shared or static library. In order to use a pre-compiled function you need to introduce it to your program via a declaration. Example:

a.h

void f();

a.cpp

void f(){/* implementation here */}

main.cpp

#include "a.h"

int main()
{
    f();
}

main()中包含"a.h"就是在声明该功能.一旦编译了a.cpp一次,就不再需要它的源代码,只要您至少具有对目标文件的访问权限,该程序就会运行,但是为了使链接程序找到功能f(),您需要声明它.

Including "a.h" in main() is declaring the function. Once you compile the a.cpp once, you don't need it's source any more, the program will run provided you have at least access to the object file, but in order for the linker to find the function f() you need to declare it.

这篇关于函数原型-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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