基本应用
this是一个指针,指向当前的对象。
其常见作用为:
const double PI = 3.14;
class People{
private:int age;
public:People(string name,int age){
this->age = age;//this是一个指针,指向当前的对象
}
/**
* 如果要返回自身,那么返回值就必须是People的引用,而不能只是People,否则返回的只是一个临时的拷贝对象
* 由于this是指针,故而返回自身需要用取值符*
*/
public:People& addAge(int addNum){
age += addNum;
return *this;
}
public:int getAge(){
return age;
}
};
int main() { People p(“小明”, 20); p.addAge(2).addAge(3).addAge(4);//利用返回自己的操作,可以实现链式编程 cout << p.getAge() << endl;
return 0;
}
```