C++学习笔记--C语言模拟this指针

xiaoxiao2025-11-13  8

都知道,C++中类的成员变量和成员函数是分开存储的,变量可以存储在堆、栈、全局区,而函数只能存在代码段,并且一个类只对应一套成员函数,那么如何通过类对象调用成员函数呢? 答案是通过this指针,类对象将this指针传递给函数,所以函数能够使用类对象的成员变量,而this指针保存的就是当前对象的地址。这个传递的行为被编译器隐藏起来了,下面通过C代码模拟this指针的传递过程。

头文件test.h

#ifndef _TEST_H_ #define _TEST_H_ typedef void Demo;//隐藏对外属性,模拟private限定符 typedef struct test//定义类 { int mi; int mj; }Test; //定义类成员函数,通过参数可以看出来通过指针传递对象 Demo* Creat(int i, int j);//模拟构造函数,返回值为模拟出来的this指针 int GetI(Demo* pThis); int GetJ(Demo* pThis); int Add(Demo* pThis, int k); void Free(Demo* pThis);//模拟析构函数 #endif // _TEST_H_

test.c

#include "test.h" #include <stdlib.h> //函数中都是通过对象指针进行数据传递使用的 Demo* Creat(int i, int j) { Test* t = (Test*)malloc(sizeof(Test)); if( NULL != t) { t->mi = i; t->mj = j; } return t; } int GetI(Demo* pThis) { Test *obj = (Test*)pThis; return obj->mi; } int GetJ(Demo* pThis) { Test *obj = (Test*)pThis; return obj->mj; } int Add(Demo* pThis, int k) { Test *obj = (Test*)pThis; return obj->mi + obj->mj + k; } void Free(Demo* pThis) { if(NULL != pThis) { free(pThis); } }

main.c

#include <stdio.h> #include <stdlib.h> #include "test.h" int main() { Test *t = Creat(1, 2); printf("getI = %d\n", GetI(t)); printf("getJ = %d\n", GetJ(t)); printf("Add = %d\n", Add(t, 3)); printf("Hello world!\n"); return 0; }

通过此代码显式的展现了C++中this指针的传递过程。

转载请注明原文地址: https://www.6miu.com/read-5039569.html

最新回复(0)