what is concept of Inline function and how it is differ from macro?(什么是内联函数的概念,它与宏有何不同?)
问题描述
可能重复:
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::f 和Foo::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.
这篇关于什么是内联函数的概念,它与宏有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是内联函数的概念,它与宏有何不同?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
