c++ 中的this指针是如何工作的?

本文通过一个具体的例子,深入探讨了C++中this指针的运作原理,详细解释了如何在成员函数内部访问和操作指向当前对象的指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 通过一个例子,看看不使用本身的this,而是自己实现THIS,了解this指针的工作机制:
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;

//
// 
//
struct  X
{
private:
	int len;
	char *ptr;
public:
	int GetLen(X* const THIS)
	{
		return THIS->len; //
	}

	char *GetPtr(X* const THIS)
	{
		return THIS->ptr;
	}

	X& Set(X* const, char *);
	X& Cat(X* const, char *);;
	X& Copy(X* const, X&);
	void Print(X* const);
};

X& X::Set(X* const THIS,char *pc)
{
	THIS->len = strlen(pc);
	THIS->ptr = new char[THIS->len];
	strcpy(THIS->ptr, pc);

	return *THIS;
}

X& X::Cat(X* const THIS,char *pc)
{
	THIS->len += strlen(pc);
	strcat(THIS->ptr, pc);
	return *THIS;
}


X& X::Copy(X* const THIS, X& x)
{
	THIS->Set(THIS, x.GetPtr(&x));
	return *THIS;
}

void X::Print(X* const THIS)
{
	cout<<THIS->ptr<<endl;
}

void main()
{
	X x;

	x.Set(&x, "hello");
	x.Cat(&x, "Yes\n\n");

	x.Print(&x);

	X y;
	y.Copy(&y, x);
	y.Print(&y);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值