码迷,mamicode.com
首页 > 其他好文 > 详细

内联(inline)函数

时间:2015-05-28 00:10:49      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

  1. 内联函数避免函数调用的开销
    将函数指定为内联函数,(通常)就是将它在程序中每个调用点上“内联地”展开。假设我们将shorterStirng定义为内联函数,则调用:
    cout<<shorterSring(s1,s2)<<endl;
    在编译时将展开为:
    cout<<(s1.size() < s2.size() ? s1 : s2)
           <<endl;
    从而消除了把shorterString写成函数的额外执行开销。
    在函数返回类型前加上关键字inline就可以将shorterString函数指定为内联函数:
    //inline version: find longer of two strings
    inline const string &
    shorterString(const string &s1, const stirng &s2){return s1.size() < s2.size() ? s1 : s2;}

  2. 把内联函数放入头文件
    内联函数应该放入头文件,这一点不同于其它函数。
    内联函数可能要在程序中定义不止一次,只要内联函数的定义在某个源文件中只出现一次,而且在所有源文件中,其定义必须是相同的。把内联函数的定义放在头文件中,可以确保在调用函数时所使用的定义是相同的,并且保证在调用点该函数的定义对编译器可见。
  3. 三种形式:

    classScreen{
    public:
        typedef std::string::size_type index;
    
        //implicitly inline when defined inside the class declaration
        char get()const{return contents[cursor];}
    
        //explicitly declared as inline;will be defined outside the class         declaraton
        inline char get(index ht, index wd)const;
    
        //inline not specified in class declaration,but can be defined inline later
        index get_cursor()const;
        //...
    };
    
    //inline declared in the class declaration; no need to repeat on the definition
    charScreen::get(index r, index c)const
    {
        index row = r * width;//compute the row location
        return contents[row + c];//offset by c to fetch specified c haracter
    }
    
    //not declared as inline in the class declaration, but ok to make inline in definnition
    inlineScreen::index Screen::get_cursor()const
    {
        return cursor;
     }

     

     





内联(inline)函数

标签:

原文地址:http://www.cnblogs.com/codetravel/p/4534526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!