什么是内联函数的概念,它是如何从宏观有什么不同? [英] what is concept of Inline function and how it is differ from macro?
问题描述
可能重复:结果
C ++内联函数?
块引用>什么是内联函数的真正概念。
我真的无法理解内联函数。
&为什么放;我应该在哪里使用内联函数?它是如何从正常功能有什么不同?
编辑:什么是宏观与放大器之间的差异;内联函数?
解决方案内联和非内联函数之间的主要语言不同的是,内联函数是从的一个定义规则豁免的,所提供的所有的定义都是相同的。
这是C ++的一个重要特征,因为它允许你写成员函数定义的类定义中,仍然能够包含在头文件中的类定义。
考虑这个头:
// stupid.h
的#ifndef H_STUPID
#定义H_STUPIDINT富(){返回8; }#万一stupid.h无法使用,如果你要包含它不止一次,因为你与
富
的多个定义结束。在申报在线
让你解决这个问题搞定。运用同样的逻辑类定义(记住,是指所有的内联成员函数隐式声明在线
),这让我们这样写:// works.h
的#ifndef H_WORKS
#定义H_WORKSFoo类
{
INT N;
上市:
无效F(){N * = 2; } //内联含蓄!
INT克()const的{返回N; } //同上
};#万一我们可以包括在尽可能多的翻译单元works.h我们喜欢,而且也没有多重定义错误
富::˚F
和富::摹
,因为那些是(隐含的)声明为inline。当然,
点$ ptty独立得多在线
也可以作为一个提示编译器以取代函数体的拷贝函数调用,但是编译器可以选择做或那样做$你是否不声明函数在线
。Possible Duplicate:
c++ inline function?What is the the real concept of inline function.
i really unable to understand the inline function.
why & where should i use inline function? How it is differ from normal function?
Edit: what is difference between macro & inline function?
解决方案The main language difference between an inline and a non-inline function is that inline functions are exempt from the one-definition rule, provided all definitions are the same.
This is a crucial feature for C++, since it allows you to write member function definitions inside class definitions and still be able to include the class definition in a header file.
Consider this header:
// stupid.h #ifndef H_STUPID #define H_STUPID int foo() { return 8; } #endif
stupid.h is not usable if you have to include it more than once, because you'll end up with multiple definitions of
foo
. Making the declarationinline
lets you get around this problem. Applying the same logic to a class definition (remember that all member functions that are defined inline are implicitly declaredinline
), this allows us to write this:// works.h #ifndef H_WORKS #define H_WORKS class Foo { int n; public: void f() { n *= 2; } // implicitly inline! int g() const { return n; } // ditto }; #endif
We can include works.h in as many translation units as we like, and there's no "multiple definition" error for
Foo::f
andFoo::g
, because those are (implicitly) declared inline.Of course
inline
also serves as a hint to the compiler to replace function calls by copies of the function body, but the compiler can choose to do or not do that pretty much independent of whether or not you declare a functioninline
.这篇关于什么是内联函数的概念,它是如何从宏观有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!