this指针

在类的成员函数(不包括静态成员函数)中,存在一个名为this的指针,该指针指向成员函数被调用时的对象。

   1 class clock {
   2     int second, minute, hour;
   3 public:
   4     clock(int h, int m, int s)
   5        : hour(h), minute(m), second(s)
   6     {
   7     }
   8     void show_time() {
   9         cout <<  second << minute << hour;
  10         //等价于 cout << this->second << this->minute << this->hour;
  11     }
  12 };
  13 int main() {
  14     clock  t1(10, 20, 30), t2(20, 30, 10);
  15     t1.show_time();
  16     t2.show_time();
  17 }

   1 class clock {
   2 public:
   3     clock &set_second(int n);
   4     clock &set_minute(int n);
   5     clock &set_hour(int n);
   6 };
   7 clock &clock::set_second(int n) {
   8     second = n;
   9     return *this;
  10 }
  11 int main() {
  12     clock time(1999, 9, 9);
  13     time.set_second(20);
  14     time.set_minute(30)
  15     time.set_hour(10);
  16     time.set_second(20).set_minute(30).set_hour(10);
  17 }

this有两种类型:以clock类为例,clock* const和const clock* const

   1 class clock {
   2 public:
   3     void show_time() const {
   4         cout <<  second << minute << hour;
   5         second++;                  //error this类型为const Date *this
   6 
   7         clock *p = (clock*)(this); // 或者clock *p = const_cast<clock*>(this);
   8         p->second++; //ok
   9     }
  10 };


CategoryCpp

C++:this指针 (2008-03-13 20:57:33由czk编辑)

ch3n2k.com | Copyright (c) 2004-2020 czk.