C++_类_this指针

定义

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

作用

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<<name<<age<<endl;
    }
private:
    string name;
    int age;
};
int main ()
{
    stu student("zhangxiang",22);
    student.prin();

    return 0;
}

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值