内联函数原型vs正则声明vs原型 [英] Inline function prototype vs regular declaration vs prototype

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

问题描述

内联函数和main函数之间有何区别:

What's the difference between inline function and then main like so:

inline double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

vs只是定期声明一个函数,例如:

vs just declaring a function regularly like:

double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

vs函数原型?

double cube(double);

int main( )
{
    cube(5);
}

double cube(double side)
{
   return side * side * side;
}

推荐答案

可以在多个转换单元(cpp文件+包含文件)中定义inline函数,这是向编译器内联该函数的提示.通常将其放在标头中,这会增加编译时间,但是可以导致更快的代码.它还允许在许多编译单元中使用该功能.

An inline function can be defined in multiple translation units (cpp file + includes), and is a hint to the compiler to inline the function. It is usually placed in a header which increases compile time, but can lead to faster code. It also allows the function to be used from many compilation units.

//cube.h
inline double cube(double side)
{
   return side * side * side;
}

//cube.cpp
int main( )
{
    cube(5);
}

定期定义它是常规方法,通常在cpp文件中定义并链接它.其他编译单元不容易使用它.

Defining it regularly is the normal method, where it's (usually) defined in a cpp file, and linked against. It is not easily used from other compilation units.

//cube.cpp
double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

原型允许您告诉编译器在链接时某个函数将存在,即使该函数尚不存在.这允许main调用该函数,即使它尚不存在.通常,原型位于标头中,因此其他编译单元可以调用该函数,而无需自己定义.这具有最快的编译时间,并且该功能可从其他编译单元轻松使用.

A prototype allows you to tell the compiler that a function will exist at link time, even if it doesn't exist quite yet. This allows main to call the function, even though it doesn't exist yet. Commonly, prototypes are in headers, so other compilation units can call the function, without defining it themselves. This has the fastest compilation time, and the function is easily used from other compilation units.

//cube.h
double cube(double);

//cube.cpp
int main( )
{
    cube(5);
}

double cube(double side)
{
   return side * side * side;
}

这篇关于内联函数原型vs正则声明vs原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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