博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++_类_this指针
阅读量:287 次
发布时间:2019-03-01

本文共 836 字,大约阅读时间需要 2 分钟。

定义

  • 系统在创建对象时,默认生成的指向当前对象的指针。这样作的目的,就是为了带来方便

作用

1、避免构造器的入参与成员名相同

using namespace std;class stu{
public: stu(string name,int age){
this->name = name; //用this来指代这个对象的name this->age = age; //name = name; //age = age; //构造器的入参与成员名相同,这样写输出的结果是错误的 } void prin() {
cout<
<
<

2、基于 this 指针的自身引用还被广泛地应用于那些支持多重串联调用的函数中。比如连续赋值。

连续赋值:a=b=c=d;:sstring &sstring::operator=(const sstring & another)  //重载赋值运算符{
if(another._str==_str) return *this; s4 = s4; //这个就调 delete [] _str; int len = strlen(another._str); strcpy(_str,another._str); return *this;}

3、this其实是指向本类对象的常指针 stu * const this

  • 注意下面两者的区别
    • class * const this; //表示this指针不可被修改
    • const class * this; //表示this指针指向的内存里面的内容不可被修改
Stu*  const & growUp(){
this->age++; return this;}

转载地址:http://psko.baihongyu.com/

你可能感兴趣的文章