This 指针和const 修饰This指针

一、This指针

每个对象都维护自己的一份数据,而成员函数定义是所有对象共享的。

以下两段程序是c++编译器对普通成员函数的内部处理

This指针是一个常量,含有当前实施调用的对象的地址

class Test
{
public:
	Test (int i)
	{
		mI = i;
	}
	int getI()
	{
		return mI;
	}
	static void Print()
	{
		printf("This is class Test.\n");
	}
protected:
private:
	int mI;
};
Test a(10);
a.getI();
Test::Print();


void Test_initilize(Test* pThis,int i)
{
	pThis->mI = i;
}
int Test_getI(Test* pThis)
{
	return pThis->mI;
}
void Test_Print()
{
	printf("This is class Test.\n");
}

Test a;
Test_initilize(&a,10);
Test_getI(&a);
Test_Print();

问题??

      调用成员函数时,如何知道是对那个对象进行数据操作呢

每个成员函数都有一个隐含的参数,指向接收消息的对象 称为This指针


This的作用:

(1) 用来区分与局部变量重名的数据成员

(2)返回当前对象

(3)  返回当前对象的地址

没学This指针的时候需要这样

class 
{
public:
	int getA(int _a,int _b)
	{
		a = _a;
		b = _b;
	}
protected:
private:
	int a;
	int b;
};
使用This指针是:

class 
{
public:
	int getA(int a,int b )
	{
		this->a = a;
		this->b = b;
	}
protected:
private:
	int a;
	int b;
};

class X
{
	int m;
public:
	void setVal(int m)
	{
		this->m = m;//区分与函数参数重名的数据成员
	}
	X& add(const X& a)
	{
		m += a.m;
		return *this;//返回当前对象
	}
	void copy(const X& a)
	{
		if(this == &a)
		{
			return;
			m = a.m;//拷贝操作
		}
	}
protected:
private:
};








#include<iostream>
using namespace std;

class Test
{
public:
	Test(int a,int b)//实质是Test(Test *this,int a,int b)
	{
		this->a = a;
		this->b = b;
	}
	void printT()
	{
		cout<<"a:"<<a<<endl;
		cout<<"b:"<<this->b<<endl;
	}
	//1 const 写在什么位置 没有关系
	//2 const 修饰的是谁?
	//3 const 修饰的是形参 a 吗?--不是
	//4 const 修饰的是属性 this-a this-b?--不是
	//实质是:void  OpVar(const Test *this int a,int b) 
	//void  OpVar(const Test *const this int a,int b) 更精确的写法
	//const 修饰的是this指针,指针指向的内存的空间不能修改
	void  OpVar(int a,int b) const//一般写在后边
	{
		a = 100;
		this->a = 100;
		this->a = 100;
		//cout<<"a:"<<a<<endl;
		cout<<"b:"<<this->b<<endl;
	}
protected:
private:
	int a;
	int b;
};

int main()
{
	Test t1(1,2);
	t1.printT();//实质是printT(&t1)
	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值