this
指针是指向对象本身
的指针.this
并不是对象的组成部分. 即, 使用sizeof(对象)
并不会受this
指针大小的影响.this
指针作为隐含参数传递到对象成员函数, 除static
修饰的函数外.this
指针可以作为参数返回; 也可一通过*this
的方式, 返回对象的副本.this
指针只能作为右值
使用, 即不能对this
指针进行赋值.- 在 非
const
函数调用时, 传递T* const
类型指针; 在const
函数调用时, 传递const T* const
类型指针.
- 下是一个使用
this
指针的例子:
#include <iostream>
class num {
private:
int m_a;
public:
num(int a) : m_a(a) {}
num *add_num(int count) {
this->m_a += count;
return this;
}
void show_num(void) { std::cout << this->m_a << std::endl; }
};
int main(void) {
num n = num{0};
n.add_num(1)->add_num(2)->add_num(3)->show_num(); // 输出:6
n.show_num(); // 输出:6
}
如果觉得有帮助,可以扫描右边的微信打赏码支持一下.