this指针

目录

一、关于this指针的一个经典问题

二、this指针的特点

(一)本质

(二)应用

1. 不使用this指针

2. 使用this指针

3. 两者代码对比

三、代码举例

1. 举例1 

2. 举例2

 


一、关于this指针的一个经典问题

当你进入一个房子后,   
你可以看见桌子、椅子、地板等,   
但是房子你是看不到全貌了。   
对于一个类的实例来说,   
你可以看到它的成员函数、成员变量,   
但是实例本身呢?   
this是一个指针,它时时刻刻指向你这个实例本身

二、this指针的特点

  • this指针的类型:类类型* const,即成员函数中,不能给this指针赋值
  • 只能在“成员函数”的内部使用 
  • this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针 
  • this指针是“成员函数”第一个隐含的指针形参,通常this指针在系统中是隐含存在的,也可以把它显式表示出来 
  • 非静态成员函数中可以直接使用this来代表指向该函数作用对象的指针,静态成员函数中不能使用this指针,因为静态成员函数并不具体作用与某个对象,因此,静态成员函数真实的参数的个数,就是程序中写出的参数个数 

(一)本质

(二)应用

1. 不使用this指针

#include<iostream>
using namespace std;
class A
{
private:
	int i;
public:
	void set(int x)
	{
		i = x;
	}
	int get()
	{
		return i;
	}
};

int main()
{
	A a;
	a.set(9);
	cout << a.get() << endl;
	return 0;
}

2. 使用this指针

#include<iostream>
using namespace std;
class A
{
private:
	int i;
public:
	void set(int x)//给私有成员变量i赋值
	{
		this->i = x;//this指针指向的是当前对象(所谓当前对象就是,谁此时调用set函数,谁就是当前对象)
		cout << "this指针保存的内存地址为:" << this << endl;
	}
	int get()
	{
		return i;
	}
};

int main()
{
	A a;
	a.set(9);//对象a调用set()函数给自己的成员变量i赋值
	cout << "对象a所在的内存地址为:" << &a << endl;
	cout << "对象a所保存的值为:" << a.get() << endl;
	cout << endl;

	A b;
	b.set(999);
	cout << "对象b所在内存地址为:" << &b << endl;
	cout << "对象b所保存的地址为:" << b.get() << endl;
}

 

3. 两者代码对比

三、代码举例

1. 举例1 

#include<iostream>
using namespace std;
class Box
{
private:
	double length;//长
	double breadth;//宽
	double height;//高
public:
	Box(double l = 2.0, double b = 2.0, double h =2.0)
	{
		cout << "Constructor called" << endl;
		length = l;
		breadth = b;
		height = h;
	}
	double Volume()//体积
	{
		return length * breadth * height;
	}
	int compare(Box box)//比较
	{
		return this->Volume() > box.Volume();
	}
};

int main()
{
	Box Box1(3.3, 1.2, 1.5);
	Box Box2(2.5, 6.0, 2.0);
	if (Box1.compare(Box2))//Box1调用的成员函数compare,所以this指针指向的是Box1
	{
		cout << "Box1 is bigger than Box2!" << endl;
	}
	else
	{
		cout << "Box1 is smaller or equal than Box2!" << endl;
	}
	return 0;
}

 

2. 举例2

代码举例2:
#include<iostream>
using namespace std;
class complex
{
	public:
		double real,imag;
		void print()
		{
			cout<<real<<","<<imag;
		}
		complex(double r,double i):real(r),imag(i)//初始化列表,complex接收传进来的两个数r和i,
		//将r传给real,将i传给img 
		{
			;
		}
		complex addone()
		{
			this->real++;//等价于real++ 
			this->print();//等价于print 
			return *this;//this指针指向了调用addone()函数的对象 
		}
};
int main()
{
	complex c1(1,1);
	complex c2(0,0);
	c2=c1.addone();//c1.anddone会调用addone函数,this指向addone()函数所作用的对象c1,
	//导致c1的real加1,也就变成了2,然后this指向的print()函数所作用的对象c1,打印c1的real=2,imag=1 
	return 0;
}

  • 20
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值