成员函数可以重载;但成员函数只能重载本类的其他成员函数。类的成员函数与普通的非成员函数以及在其他类中声明的函数不相关,也不能重载它们。
成员函数可被重载
成员函数只能重载本类的其他成员函数。类的成员函数与普通的非成员函数以及在其他类中声明的函数不相关,也不能重载它们。重载的成员函数和普通函数应用相同的规则:两个重载成员的形参数量和类型不能完全相同。调用非成员重载函数所用到的函数匹配过程也应用于重载成员函数的调用。
定义重载成员函数
为了举例说明重载,可以给出 screen 类的两个重载成员,用于从窗口返回一个特定字符。两个重载成员中,一个版本返回由当前光标指示的字符,另一个返回指定行列处的字符:
class screen {public:typedef std::string::size_type index;// return character at the cursor or at a given positionchar get() const { return contents[cursor]; }char get(index ht, index wd) const;// remaining membersprivate:std::string contents;index cursor;index height, width;};与任意的重载函数一样,给指定的函数调用提供适当数目和类型的实参来选择运行哪个版本:
screen myscreen;char ch = myscreen.get();// calls screen::get()ch = myscreen.get(0,0); // calls screen::get(index, index)推荐教程:《c 视频教程》