第50 课C++对象模型分析——成员函数(上)

类中的成员函数位于代码段中
调用成员函数时对象地址作为参数隐式传递
成员函数通过对象地址访问成员变量
C++语法规则隐藏了对象地址的传递过程

#include<iostream>
#include <string>

using namespace std;

class Demo
{
    int mi;
    int mj;
public:
    Demo(int i, int j)
    {
       mi = i;
       mj = j;
    }
    int getI()
    {
        return mi;
    }
    int getJ()
    {
        return mj;
    }
    int add(int value)
    {
        return mi + mj + value;
    }
};

int main()
{
    Demo d(1,2);
    cout << "sizeof(d) =" << sizeof(d) <<endl;
    cout << "getI()=" << d.getI() << endl;
    cout << "getJ()=" << d.getJ() << endl;
    cout << "d.add(3)=" << d.add(3) << endl;

    return 0;
}

d.getI()
d对象的地址被传到了getI这个函数的内部,但是传递过程在C++代码中是看不到的。深度挖掘的就是编译器背后的故事,此时就需要用到C语言了,用C语言实现这个面向对象的程序。

50-2.h

#ifndef _50_2_H_
#define _50_2_H_

typedef void Demo;

Demo* Demo_Create(int i, int j);
int Demo_GetI(Demo* pThis);
int Demo_GetJ(Demo* pThis);
int Demo_Add(Demo* pThis, int value);
void Demo_Free(Demo* pThis);

#endif

50-2.c

#include "50-2.h"
#include "malloc.h"

struct ClassDemo
{
    int mi;
    int mj;
};

Demo* Demo_Create(int i, int j)
{
    struct ClassDemo* ret = (struct ClassDemo*)malloc(sizeof(struct ClassDemo));
    
    if( ret != NULL )
    {
        ret->mi = i;
        ret->mj = j;
    }
    
    return ret;
}

int Demo_GetI(Demo* pThis)
{
     struct ClassDemo* obj = (struct ClassDemo*)pThis;
     
     return obj->mi;
}

int Demo_GetJ(Demo* pThis)
{
    struct ClassDemo* obj = (struct ClassDemo*)pThis;
     
    return obj->mj;
}

int Demo_Add(Demo* pThis, int value)
{
    struct ClassDemo* obj = (struct ClassDemo*)pThis;
     
    return obj->mi + obj->mj + value;
}

void Demo_Free(Demo* pThis)
{
    free(pThis);
}

main.c

#include <stdio.h>
#include "50-2.h"

int main()
{
    Demo* d = Demo_Create(1, 2);             // Demo* d = new Demo(1, 2);
    
    printf("d.mi = %d\n", Demo_GetI(d));     // d->getI();
    printf("d.mj = %d\n", Demo_GetJ(d));     // d->getJ();
    printf("Add(3) = %d\n", Demo_Add(d, 3));    // d->add(3);
    
    // d->mi = 100;
    
    Demo_Free(d);
    
    return 0;
}

面向对象不是C++专属的,依然可以用C语言写面向对象

猜你喜欢

转载自www.cnblogs.com/-glb/p/11965580.html