显式指定 inline 成员函数

在类内部定义的成员函数,例如不接受实参的 get 成员,将自动作为inline 处理。也就是说,当它们被调用时,编译器将试图在同一行内扩展该函数。也可以显式地将成员函数声明为 inline:

class Screen {
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 declaration
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
char Screen::get(index r, index c) const
{
index row = r * width; // compute the row location
return contents[row + c]; // offset by c to fetch specified character
}
// not declared as inline in the class declaration, but ok to ake

inline in definition
inline Screen::index Screen::get_cursor() const
{
return cursor;
}

可以在类定义体内部指定一个成员为 inline,作为其声明的一部分。或者,也可以在类定义外部的函数定义上指定 inline。在声明和定义处指定 inline都是合法的。在类的外部定义 inline 的一个好处是可以使得类比较容易阅读。

像其他 inline 一样,inline 成员函数的定义必须在调用该函数的每个源文件中是可见的。不在类定义体内定义的 inline成员函数,其定义通常应放在有类定义的同一头文件中。

posted @ 2018-05-05 22:24  刘-皇叔  阅读(436)  评论(0)    收藏  举报