博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C/CPP-类对象的this指针

Posted on 2023-03-13 09:37  乔55  阅读(14)  评论(0编辑  收藏  举报

this指针在于什么地方

1. // 每个普通成员函数的形参都隐含了:Time* const this,Time是类
2. // const成员函数形参隐含了:const Time* const this
3. // 调用成员函数时,会把该对象的地址传递给this指针
4. // void getK()const{} 等价于:void getK(const Time* const this){}
5. // 在类内,可打印当前对象的地址:cout << this << endl;
  • 每个普通成员函数的形参隐含了:Time* const this,它指向调用该函数的对象
  • const成员函数的形参隐含了:const Time* const this
  • 调用成员函数时,隐式地把调用该成员函数的对象的地址传递给该成员函数
  • void getK()const{}等价于void getK(const Time* const this)

this返回对象本身

  • 在非静态成员变量中返回对象本身,可用return* this;