一、this指針介紹
概念:this指針是成員函數的一個隱式參數,在類中本質上就是對象的指針(常量指針)
特點:
在成員函數中可通過this指針區別成員變量與形參變量
this可以顯式調用
示例代碼:
class Cperson{private:int age;float height;public:void InitPerson(int age,float height);};void Cperson::InitPerson(int age,float height){this->age=age;this->height=height;}
二、返回*this成員函數
概念:返回值是*this,也就是返回調用此成員函數的對象的自身引用,返回值類型為對象引用類型
class Person{private:int age;public:Person& setAge(int age);//返回自身引用};Person& Person::setAge(int age){this->age=age;return *this;//返回*this(自身引用)}
從const成員函數返回*this:如果一個const成員函數返回*this,那么此函數的返回值類型是常量引用:比如上面的代碼中的setAge函數變為常量成員函數<