1、C++ this 指针
类的成员函数可以访问类的数据,一般类成员和函数操作都是通过对象,每个对象都拥有一个指针:this
指针,通过this指针来访问自己的地址。this
指针并不是对象的一部分,this
指针所占的内存大小是不会反应在sizeof
操作符上的。this
指针的类型取决于使用this指针的成员函数类型以及对象类型。this
只能在成员函数中使用。全局函数,静态函数都不能使用 this
。this
在成员函数的开始执行前构造的,在成员的执行结束后清除。this
指针只有在成员函数中才有定义。
2、C++ this 指针的使用
在类的非静态成员函数中返回类对象本身时,可以使用圆点运算符(*this
).,箭头运算符this->
,另外,也可以返回关于*this
的引用。
例如,
#include#include using namespace std;class Person{ int sno; string sname; int age; int grade;public: Person(int s=0,string n="",int a=0,int g=0) { sno=s; sname=n; age=a; grade=g; } void Setsname(int sn) //使用this指针进行赋值 { this->sname=sn; } int Setage(int a) { this->age=a; return (*this).age; //使用this指针返回该对象的年龄 } void print() { cout<<"sname = "< sname< grade<