4、定义重载函数
class Screen
{
public:
typedef std::string::size_type index;
//一下两个函数构成重载
char get() const
{
return contents[cursor];
}
char get(index ht,index wd) const;
private:
std::string contents;
index cursor;
index height,width;
};
使用:
Screen myScreen;
char ch = myScreen.get();
ch = myScreen.get(0,0);
5、显式指定inline函数
在类内部定义的成员函数,默认就是inline函数。但是也可以显式的将成员函数指定为inline:
class Screen
{
public:
typedef std::string::size_type index;
//默认就是inline函数
char get() const
{
return contents[cursor];
}
inline char get(index ht,index wd) const;
index get_cursor() const;
private:
std::string contents;
index cursor;
index height,width;
};
//已经在类体中声明为inline了,就没必要再次声明
char Screen::get(index r,index c) const
{
index row = r * width;
return contents[row + c];
}
//即使没有在类体中声明,也可以在外面补上...
inline Screen::index Screen::get_cursor() const
{
return cursor;
}
在声明和定义处指定inline都是合法的。在类的外部定义inline的一个好处是可以使得类比较容易阅读。
【最佳实践】
像其他inline一样,inline成员函数的定义必须在调用该函数的每个源文件中是可见的。不在类定义体内定义的inline成员函数,其定义通常应放在有类定义的同一头文件中。