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

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

问题描述

可能重复:
c++内联函数?

内联函数的真正概念是什么.

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.

这是 C++ 的一个关键特性,因为它允许您在类定义中编写成员函数定义,并且仍然能够将类定义包含在头文件中.

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.

考虑这个标题:

// stupid.h
#ifndef H_STUPID
#define H_STUPID

int foo() { return 8; }

#endif

如果您必须多次包含

stupid.h,则它是不可用的,因为您最终会得到 foo 的多个定义.使声明 inline 可以让您解决这个问题.将相同的逻辑应用于类定义(请记住,内联定义的所有成员函数都隐式声明为 inline),这允许我们这样写:

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

我们可以在任意数量的翻译单元中包含works.h,并且对于Foo::fFoo::g 没有多重定义"错误,因为它们(隐式)声明为内联.

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.

当然,inline 也可以作为提示编译器用函数体的副本替换函数调用,但是编译器可以选择做或不做,这与是否你声明了一个函数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天全站免登陆