C++ this指针(解析用法及意义)

this指针

1、C语言里访问类的成员(变量、函数)需要传一个对象的指针,下面例子

#include

class MyClass
{
public:
	int x, y;
	void test(MyClass* that)
	{
		printf("x=%d,y=%d \n",that->x,that->y);
	}
};

int main()
{
	
	MyClass obj;
	obj.x = 10;//点访问
	obj.y = 20;
	obj.test(&obj);

	//MyClass* obj1;
	//obj1->x = 10;//指针使用箭头访问
	//obj1->y = 20;

	return 0;
}

2、C++的this指针

(1)下面用this的方法实际与上面的方法一致,为了在访问成员函数时不用每次都要多传递一个对象指针参数;this是编译器的简洁方式

#include

class MyClass
{
public:
	int x, y;
	void test()
	{
        //实际上this指针的类型就是对象指针,比如这里就是MyClass* 类型的
		printf("x=%d,y=%d \n",this->x,this->y);
	}
};

int main()
{
	
	MyClass obj;
	obj.x = 10;//点访问
	obj.y = 20;
	obj.test();

	return 0;
}

(2)this任意访问所有成员(变量、函数)

#include

class MyClass
{
public:
	int x, y;
	int add()
	{
		return this->x + this->y + 10;
	}
	void test()
	{
		printf("x=%d,y=%d \n",this->x,this->y);
		printf("x+y+10=%d \n", this->add());
	}
};

int main()
{
	
	MyClass obj;
	obj.x = 10;//点访问
	obj.y = 20;
	obj.test();

	return 0;
}

(3)来验证this和对象指针的地址是否一致

#include

class MyClass
{
public:
	int x, y;
	void test()
	{
		printf("this地址: %p \n", this);
	}
};

int main()
{
	
	MyClass obj;
	printf("obj地址: %p \n", &obj);
	obj.test();

	return 0;
}

C++ this指针(解析用法及意义)_第1张图片

(4)成员重名时 this 和 :: 的使用(包括成员函数)

#include
int x = 10;
class MyClass
{
public:
	int x, y;
	void test()
	{
		//还可以省略this
		printf("x=%d,y=%d \n", x,y);
	}
	void test1(int x)
	{
		//就近原则使用参数x
		printf("x=%d \n", x);
		//想要访问成员变量x就需要this指定
		printf("x=%d \n", this->x);
		//想要访问全局变量x加两个冒号 ::
		printf("x=%d \n", ::x);
	}
};

int main()
{
	MyClass obj;
	obj.x = 1;
	obj.y = 2;
	obj.test();
	obj.test1(3);

	return 0;
}

C++ this指针(解析用法及意义)_第2张图片

你可能感兴趣的:(C++,c++,指针)