//类定义(2) //同一类型的多个数据成员,适用类型别名简化类 //定义重载成员函数 //显式指定inline内联成员函数 #include <iostream> using namespace std; //导入名称空间 //做窗口设计:窗口可以改变大小,多行文本框区域可以输入文字 class Screen{ //1、写在类内部的函数都称为内联函数 public: typedef std::string::size_type index; //定义别名 Screen(index ht = 0, index wd = 0): contents(ht * wd, 'b'), cursor(0), height(ht), width(wd){}; //定义构造函数 Screen(index ht, index wd, const std::string &conts); //构造函数声明 char get() const; inline char get(index r, index c) const; //3、此处声明处写了inline使之成为内联函数 private: std::string contents; //代表文本框中的文字 index cursor;//光标的位置 index height, width; //文本框的高度和宽度 }; //显式表面内联函数 //2、写了inline,使之称为内联函数,get函数定义 inline char Screen::get() const{ return contents[cursor]; //返回当前光标的位置 } //重载的get函数定义 char Screen::get(index r, index c) const{ //返回指定位置的行和列,r为行数,c为列数 index row = r * width; return contents[row + c]; } //定义构造函数 Screen::Screen(index ht, index wd, const std::string &conts):contents(conts), cursor(0), height(ht), width(wd){}; int main(){ Screen a(10, 100); cout << a.get() << endl; cout << a.get(2, 8) << endl; Screen b(3, 6, "hello screen class"); cout << b.get() << endl; cout << b.get(2,3) << endl; //get函数重载 Screen::index idx; //在类的外部也可以使用index cout << "测试一下" << endl; return 0; }
C++面向对象程序语言设计———类定义(2)
最新推荐文章于 2022-05-31 20:45:50 发布