类中的this指针

类中的this指针

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>

#if 0

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

作用:
1,避免构造器的入参与成员名相同。
2,基于 this 指针的自身引用还被广泛地应用于那些
支持多重串联调用的函数中 比如连续赋值

#endif


class Stu
{
public:
	Stu(string name=0, int age=0)
		//:name(name), age(age)
	{
		this->name = name; //用this来区别是入参还是数据成员
		this->age = age;
		cout << "this" << this << endl;
	}

	void display()
	{
		cout << name << "---" << age << endl;
	}

	Stu * growUp()
	{
		this->age++;
		return this;
	}

	Stu & rankUp()
	{
		this->age++;
		return *this;
	}

private:
	string name; //养成好的习惯 对类内的数据成员格式写成
	int age;     //_name _age
};



int _tmain(int argc, _TCHAR* argv[])
{
	Stu s("bob",16);
	cout << "&s:" << &s << endl; //为了证明this所指向的地址
	s.display();

	//s.growUp()->growUp()->growUp()->growUp()->display(); 
	//返回为this指针 为s的指针 s并没有消失 所以可以连续指下去

	s.rankUp().rankUp().rankUp().rankUp().display();

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值