this指针的使用
1.在类的非静态成员函数中返回类对象本身的时候,直接使用 return *this
,比如类的默认取址运算符重载函数,另外,也可以返回*this
的引用,这样可以像输入输出流那样进行“级联”操作;
2.修改类成员变量或参数与成员变量名相同时,如this->a = a
(写成a = a
编译不过);
3.在class
定义时要用到类型变量自身时,因为这时候还不知道变量名,就用this
这样的指针来使用变量自身。
this指针注意点
1.C++
中this
关键字是一个指向对象自己的一个常量指针,不能给this
赋值;
2.只有成员函数才有this
指针,友元函数不是类的成员函数,没有this
指针;
3.同样静态函数也是没有this
指针的,静态函数如同静态变量一样,不属于具体的哪一个对象;
4.this
指针作用域在类成员函数内部,在类外也无法获取;
5.thi
s指针并不是对象的一部分,this
指针所占的内存大小是不会反应在sizeof
操作符上的。
问题
1.一个类中的不同对象在调用自己的成员函数时,其实它们调用的是同一段函数代码,那么成员函数如何知道要访问哪个对象的数据成员呢?
没错,就是通过this
指针。每个对象都拥有一个this
指针,this
指针记录对象的内存地址,当我们调用成员函数时,成员函数默认第一个参数为T* const register this
,大多数编译器通过ecx
寄存器传递this
指针,通过 this
这个隐式参数可以访问该对象的数据成员。
2.类的成员函数为什么不能用static
和const
同时修饰?
类中用const
修饰的函数通常用来防止修改对象的数据成员,函数末尾的const
是用来修饰this
指针,防止在函数内对数据成员进行修改,而静态函数中是没有this
指针的,无法访问到对象的数据成员,与C++ static
语义冲突,所以不能。
代码涉及内容
使用this
指针;
返回*this
;
从const成员函数返回*this
;
基于const
的重载;
可变的数据成员 mutable
;
1 |
|