#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;
}