【C++】C++中this指针的介绍及使用
this指针的介绍及使用
- 1.this指针的作用
- 示例代码1:(this指针存放当前对象的地址)
- 示例代码2:(this指针的使用)
- 2.this指针的写法
- 示例代码:
1.this指针的作用
Cat &cmpAge(Cat &other)
{if(other.age>age)return other;elsereturn *this;
}
用这个例子引出this指针:
指向当前对象的一个指针,哪个对象调用成员函数,this指针就指向该对象
示例代码1:(this指针存放当前对象的地址)
#include <iostream>using namespace std;/*引入this指针:C++专门用来指向当前对象地址的一个指针当前对象是谁,this指针就自动存放了谁的地址当前对象:谁调用了成员函数,谁就是当前对象
*/
class Rect
{
public:/*底层原理:当前对象.show();Rect *this=&当前对象 */void show(){cout<<"this指针打印出来的地址是当前对象的地址: "<<this<<endl;}
};int main(int argc,char **argv)
{//创建矩形类的对象Rect r1;Rect r2;cout<<"r1的地址: "<<&r1<<endl;cout<<"r2的地址: "<<&r2<<endl;//当前对象:谁(r1)调用了成员函数,谁(r1)就是当前对象r1.show();//当前对象:谁(r2)调用了成员函数,谁(r2)就是当前对象r2.show();
}/*
执行结果:r1的地址: 0x7ffdf90a5cb6r2的地址: 0x7ffdf90a5cb7this指针打印出来的地址是当前对象的地址: 0x7ffdf90a5cb6this指针打印出来的地址是当前对象的地址: 0x7ffdf90a5cb7
*/
示例代码2:(this指针的使用)
#include <iostream>using namespace std;/*引入this指针:C++专门用来指向当前对象地址的一个指针当前对象是谁,this指针就自动存放了谁的地址定义方法:比较两个矩形对象的大小(按照w和h比较,要求w,h都同时大于另外一个矩形),返回较大的那个对象
*/
class Rect
{
public://定义方法给w,h设置值,间接地使用w和hvoid setAttr(float _w,float _h);//比较两个矩形的大小Rect compare(Rect &other){if((this->w)>other.w && (this->h)>other.h){return *this;}elsereturn other;}void show(){cout<<"宽: "<<w<<endl;cout<<"高: "<<h<<endl;}
private://属性float w; float h;
};void Rect::setAttr(float _w,float _h)
{w=_w;h=_h;
}int main(int argc,char **argv)
{//创建矩形类的对象Rect r1;Rect r2;//设置宽高r1.setAttr(9.8,5.6);r2.setAttr(1.2,0.5);//比较大小//写法1:当前对象就是r1//Rect temp=r1.compare(r2);//temp.show();//写法2:当前对象就是r2Rect temp=r2.compare(r1);temp.show();
}/*
执行结果:宽: 9.8高: 5.6
*/
2.this指针的写法
this->age //指针调用
(*this).age //this解引用
示例代码:
#include <iostream>using namespace std;/*this指针平时写成员函数代码,可以省略的
*/
class Rect
{
public:void show(){}void setAttr(float _w,float _h){//写法1:标准的写法-->写全面//this->w=_w;//this->h=_h;//写法2:省略this的写法w=_w;h=_h;}
private:float w;float h;
};int main(int argc,char **argv)
{Rect r1;Rect r2;r1.setAttr(1.2,0.8);}