C实现面向对象的猜想

#include <stdio.h>
#include <string.h>

typedef struct
{
    unsigned id;
    char name[10];
    unsigned age;
} Student;

void Constructor_parm(Student* this, const unsigned id, const char name[10], const unsigned age)
{
    this->id = id;
    strncpy(this->name,name,10);
    this->age = age;
}

void Constructor_ref(Student* this,const Student* s)
{
    *this = *s;
    //同类型结构体相互赋值,整块数据对拷
}

void Destructor(Student* this)
{
    printf("Byebye %s\n",this->name);
}

void Show(const Student* this)
{
    printf("-------------------");
    printf("%u %s %u\n",this->id,this->name,this->age);
}

int main(void) {

    Student s1;
    Constructor_parm(&s1,10086,"zhangsan",18);
    Show(&s1);

    Student s2;
    Constructor_ref(&s2,&s1);
    Show(&s2);

    strncpy(s2.name,"lisi",10);// 主要看一下结构体相互赋值

    Show(&s1);
    Show(&s2);

    Destructor(&s1);
    Destructor(&s2);

    return 0;
}
#include <stdio.h>

struct Student;
typedef struct Student Student;

struct Student
{
    //数据
    int m_id;

    int (*getValue)(Student* this);
    void (*setValue)(Student* this, int a);
    //想在类中实现构造和析构,在调用初始化函数时,给他们赋值,
    //但是由于不能提前给构造constructor赋值Constructor
    //导致找不到Constructor函数,无法完成初始化,BUG!!!
    //void (*constructor)(Student* this,int a);
    //void (*destructor)(Student* this);
};

int GetValue(Student* this)
{
    return this->m_id;
}

void SetValue(Student* this, int a)
{
    this->m_id = a;
}

//析构函数
void Destructor(Student* this)
{
    printf("析构函数完成\n");
}

//构造函数
void Constructor(Student* this,int a)
{
    this->m_id = a;
    this->getValue = &GetValue;
    this->setValue = &SetValue;
    printf("构造函数完成\n");
}

Student* new(int a)
{
    Student* this= (Student*)malloc(sizeof(Student));
    Constructor(this,a);
    return this;
}

void delete(Student* this)
{
    Destructor(this);
    free(this);
}

int main(int argc, char *argv[])
{
    Student A;
    Constructor(&A,999);

    A.setValue(&A,10086);
    printf("%d\n",A.getValue(&A));

    Destructor(&A);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值