//this指针的应用 #include <iostream> #include <string> using namespace std; class Person{ public: Person(const std::string &name, const std::string &addr){ //如果参数名字与原来数据对象名字相同,就需要用this this->name = name; address = addr; } std::string getName() const{ return this->name; //this指向当前的对象 } std::string getAddress() const{ return this->address; //this指针可以不写 } private: std::string name; std::string address; }; //屏幕上的窗口 class Screen{ public: typedef std::string::size_type index; //重命名 Screen(index ht = 0, index wd = 0) :contents(ht * wd, 'A'), cursor(0), height(ht), width(wd), access_ctr(0) {} char get() const { return contents[cursor];} char get(index r, index c) const{ index row = r * width; return contents[row + c]; } Screen &move(index r, index c); //把当前光标移动到某行某列, 修改为返回类的引用,则返回的就是一个对象 void set(index, index, char); //行、列、字符 Screen& set(char); //改变光标当前位置的字符 const Screen& display(std::ostream &os) const{ //以输出流os为参数 //++access_ctr; //const函数不能对函数的数据进行修改 ++access_ctr; //声明中加了mutable,使它成为可变成员 do_dispaly(os); return *this; } Screen& display(std::ostream &os){ //基于const的重载 ++access_ctr; do_dispaly(os); return *this; } private: std::string contents; index cursor; //光标 index height, width; //窗口的高度、宽度 mutable size_t access_ctr; //计数器变量 , 加了可变的标记 //const函数返回类型必须是const,就不能修改数据 void do_dispaly(std::ostream &os) const{ //为常函数,没有修改内容 os << contents; } }; Screen& Screen::move(index r, index c){ //改变当前光标的位置 index row = r * width; cursor = row + c; return *this; //使用this指针返回对象,this必须写 } void Screen::set(index r, index c, char ch){ index row = r * width; contents[row + c] = ch; } Screen& Screen::set(char c){ contents[cursor] = c; //改变当前光标位置的字符 return *this; } int main(){ Person p("张飞", "花园街5号"); // 创建对象,并初始化,this指向类的当前对象 Person p2("刘备", "花园街6号"); cout << p.getName() << endl; //此时this指向p cout << p2.getAddress() << endl; //此时this指向p2 Screen myScreen(5, 3); cout << myScreen.get() << endl; myScreen.set(3, 2, 'B'); cout << myScreen.get(3, 2) << endl; //这两行是重点 //myScreen.move(2, 3); //myScreen.set('C'); //更简单的写法,此时需要修改move函数,用this指针返回对象 myScreen.move(2, 3).set('C').display(cout).set('k').display(cout); //调用重载的display cout << endl; myScreen.move(4, 1).set('X').move(4, 2).set('Y').move(4, 2).set('Z'); cout << myScreen.get() << endl; //获得当前光标的位置 myScreen.display(cout); //普通的display,调用const函数 return 0; }
C++面向对象程序设计——(this指针)
最新推荐文章于 2022-10-19 19:21:05 发布