类中的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;
}