【C++】this指针与成员函数

来源

https://blog.csdn.net/qq_37375427/article/details/78739564

对象的构成

  1. 从面向对象的角度
    属性(成员变量)+ 方法(成员函数)
  2. 从程序运行的角度
    数据+函数
    数据:栈、堆、全局数据区
    函数:只能代码段

代码示例

#include <iostream>
using namespace std;
class Test
{
private:
	int m_private;
public:
	int m_public;
	Test(int num) { m_private = num; };
	Test(const Test& t) { m_private = t.m_private; };
	int GetMP() { return m_private; };
	void Print() { cout << "this = " << this << endl; };
};

int main()
{
	Test t1(1);
	Test t2(2);
	Test t3(3);

	cout << "t1.getMP() = " << t1.GetMP() << endl;
	cout << "&t1 = " << &t1 << endl;
	t1.Print();

	cout << "t2.getMP() = " << t2.GetMP() << endl;
	cout << "&t2 = " << &t2 << endl;
	t1.Print();

	cout << "t3.getMP() = " << t3.GetMP() << endl;
	cout << "&t3 = " << &t3 << endl;
	t1.Print();

	return 0;
}

运行结果:

t1.getMP() = 1
&t1 = 009EF904
this = 009EF904
t2.getMP() = 2
&t2 = 009EF8F4
this = 009EF904
t3.getMP() = 3
&t3 = 009EF8E4
this = 009EF904

结论

  1. 每一个对象和其this所指的地址是一样的(this只能在类成员函数中使用,专属于某一个具体的对象
  2. 每一个对象拥有自己独立的属性(成员变量),分配单独的内存空间
  3. 所有的对象共享类的方法
  4. 方法能够直接访问对象的属性
  5. 方法中的隐藏参数this指针用于指代当前对象

猜你喜欢

转载自blog.csdn.net/vict_wang/article/details/88751333