什么是内联函数的概念,它是如何从宏观有什么不同? [英] what is concept of Inline function and how it is differ from macro?

查看:161
本文介绍了什么是内联函数的概念,它是如何从宏观有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
   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 declaration inline 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 declared inline), 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 and Foo::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 function inline.

这篇关于什么是内联函数的概念,它是如何从宏观有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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