zoukankan      html  css  js  c++  java
  • 内联函数

    • inline 函数避免函数调用的开销
    • 定义并使用一个inline函数
       1 #include <iostream>
       2 using namespace std;
       3 inline const string& longer(const string &s1, const string &s2)
       4 {
       5     return s1.size() > s2.size() ? s1 : s2;
       6 }
       7 int main()
       8 {
       9     string s1 = "222",s2 = "333";
      10     cout << longer(s1,s2);
      11     return 0;
      12 }

      输出:

    • 对于下面的声明和定义,你会将哪个放在头文件,哪个放
      在程序文本文件呢?为什么?
      (a) inline bool eq(const BigInt&, const
      BigInt&) {...}
      (b) void putValues(int *arr, int size);
      
      (a)虽然是一个函数定义,但这是一个内联函数的定义,也应该放在头文件中。
      因为:内联函数的定义对编译器而言必须是可见的,以便编译器能够在调用点
      内联展开该函数的代码,这样一来,仅有函数原型是不够的;而且内联函数有
      可能在程序中定义不止一次,这时必须保证在所有源文件中,其定义是完全相
      同的。把内联函数的定义放在头文件中,可以确保在调用函数时所使用的定义
      式相同的,并且保证在调用点该函数的定义对编译器是可见的。
      
      (b)是函数声明,适合放于头文件中。 
    •  1 #include <iostream>
       2 using namespace std;
       3 
       4 int main()
       5 {
       6     string s1 = "222",s2 = "333";
       7     cout << longer(s1,s2);
       8     return 0;
       9 }
      10 //把定义放在此处,无法执行程序,因为调用inlin函数时编译器并不知道该函数的定义
      11 inline const string& longer(const string &s1, const string &s2)
      12 {
      13     return s1.size() > s2.size() ? s1 : s2;
      14 }

      如果是普通函数,会调到函数定义的地方执行,而内敛函数则是原地展开,必须马上知道其定义,所以应将定义放入头文件中,因为#include过了,所以可以知道定义

  • 相关阅读:
    一张图片入门Python
    4.1. 如何在Windows环境下开发Python
    你必须知道的EF知识和经验
    XUnit的使用
    如何使用NUnit
    Entity Framework 不支持DefaultValue
    Have You Ever Wondered About the Difference Between NOT NULL and DEFAULT?
    Validation failed for one or more entities. See 'EntityValidationErrors' property for more details
    Entity Framework 与多线程
    sqlite中的自增主键
  • 原文地址:https://www.cnblogs.com/2020R/p/13184933.html
Copyright © 2011-2022 走看看