内联函数

来源:互联网 发布:老男孩linux培训 编辑:程序博客网 时间:2024/06/06 06:32

基本思想:将每个函数调用以它的代码体来替换,很可能会增加整个目标代码的体积

inline关键字必须和函数体定义放在一起才可以实现内联
一般而言,定义在类内部的函数,将自动内联

//screen类描述
//成员变量:int类型的窗口宽、高及光标位置 string类型的窗口内容
//成员函数:构造函数:定义窗口的大小
// 移动光标函数 和读取给定位置的字符函数

Screen.h#include<string>using namespace std;    class Screen{private:    int  height = 0;    int width = 0;    int cursor = 0;    string contents;public:    Screen(int h, int w , char c) :height(h), width(w) ,contents(h*w , c){}    Screen() = default;    char get() { return contents[cursor]; }//隐式内联    inline char get(int h, int w);//显示内联    //Screen &mov(int h , int w);//在定义处内联    void mov(int h , int w);};char Screen::get(int h, int w){    int loc = width * h+w;    return contents[loc];} /*inline Screen& Screen::mov(int h, int w){     this->cursor = h*width + w;     return *this;}*/ inline void Screen::mov(int h, int w){     this->cursor = h*width + w; }
main.cpp#include"Screen.h"#include<iostream>int main(){    Screen sc(10, 20, 'w');    cout<<sc.get()<<endl;    cout << sc.get(3, 5);    sc.mov(3, 5);//sc的cursor值发生变化    return 0;}
0 0
原创粉丝点击