C++中this指针的介绍及使用实例讲解
作者:秋风&萧瑟
这篇文章主要介绍了C++中this指针的介绍及使用实例讲解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
this指针的介绍及使用
1.this指针的作用
Cat &cmpAge(Cat &other)
{
if(other.age>age)
return other;
else
return *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的地址: 0x7ffdf90a5cb6
r2的地址: 0x7ffdf90a5cb7
this指针打印出来的地址是当前对象的地址: 0x7ffdf90a5cb6
this指针打印出来的地址是当前对象的地址: 0x7ffdf90a5cb7
*/示例代码2:(this指针的使用)
#include <iostream>
using namespace std;
/*
引入this指针:C++专门用来指向当前对象地址的一个指针
当前对象是谁,this指针就自动存放了谁的地址
定义方法:比较两个矩形对象的大小(按照w和h比较,要求w,h都同时大于另外一个矩形),返回较大的那个对象
*/
class Rect
{
public:
//定义方法给w,h设置值,间接地使用w和h
void setAttr(float _w,float _h);
//比较两个矩形的大小
Rect compare(Rect &other)
{
if((this->w)>other.w && (this->h)>other.h)
{
return *this;
}
else
return 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:当前对象就是r2
Rect 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);
}到此这篇关于C++中this指针的介绍及使用的文章就介绍到这了,更多相关C++ this指针内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
