通过一个例子,看看不使用本身的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);
}