本文为C语言结构的应用总结,C语言没有类的概念,但可以通过结构体构建一个类似类的操作概念。下文是使用的场景代码,由于水平有限,错误之处请各位大神指出。在此抛砖引玉,希望做嵌入式的的人能提供更多的应用的典型案例。
#include#include/*结构体定义 */ //只有结构类型的定义 struct stuff { char job[20]; int age; float height; }; //含有结构体类型的结构体变量初始化定义 struct stuff1 { char job[20]; int age; float height; }Hu; //struct stuff1 Hu //就相当于这样子 // 结构体不能再用来定义同类型的结构体变量,一锤子买卖; struct { char job[20]; int age; float height; }Hu1;//这种类型的结构体变量只能有这么一个,不能去定义其他的 /*结构体别名声明 */ typedef struct Stu { char job[20]; int age; float height; }Stuff,*PtrStuff; Stuff Sam;//等于 struct Stu Sam; PtrStuff pSam;//等于 struct Stu *Sam; /*结构体与其他类型 */ typedef struct arraychange { int cnt; char pc[0]; }arraychange;//pc数组只能放在最后,不能调换位置;柔性数组,少用; struct check { union { char a; }; int i; }CheckSystem; //系统内存大小端测试,结构体与联合体结合 struct structureA { struct structureB { int c; }b; //必须要有实体才能够在后面使用struct structureB bb; struct structureB bb; }a;//结构体中含有结构体; //函数可以用结构体元素,结构体,结构体指针做参数;用元素与普通没什么区别,用结构体则拷贝副本,指针是唯一的;函数可以返回结构体,使用指针的效率高 void func1(int par); //结构体元素 Stuff func2(Stuff par); //结构体,返回结构体 void func3(PtrStuff par); //结构体指针 void print(Stuff par); //结构体含有函数指针做元素,这样就可以实现类似面向对象的类封装 int fun1(int age,int weight); void fun2(int age,int weight); struct Fun { int age; int weight; int (*pfun1)(int age,int weight); //函数还有一个int返回值,两个int参数 void (*pfun2)(int age,int weight); //函数没有返回值,两个int参数 }; int main(void) { /*结构体作为函数参数 */ Stuff test,tmptest; PtrStuff ptest=&test; /*结构体含有函数指针*/ struct Fun myfun={10,45,fun1,fun2}; struct Fun *ptrmyfun=&myfun; int age=22,weight=60,temp=0; /*结构体作为函数参数 */ strcpy(test.job,"manager"); test.age=25; test.height=1.65; func1(test.age); tmptest=func2(test); print(tmptest); func3(ptest); print(test); /*结构体含有函数指针*/ temp=myfun.pfun1(age,weight); //成员调用函数 printf("temp %d\n",temp); myfun.pfun2(age,weight); //成员调用函数 myfun.age=80; myfun.weight=65; temp=ptrmyfun->pfun1(myfun.age,myfun.weight); //指针调用函数 printf("temp %d\n",temp); ptrmyfun->pfun2(myfun.age,myfun.weight); //指针调用函数 return 0; } void print(Stuff par) { printf("your job is:%s\n",par.job); printf("your age is:%d\n",par.age); printf("your height is:%f\n",par.height); } void func1(int par) { printf("your age is:%d\n",par); } Stuff func2(Stuff par) { strcpy(par.job,"Engineer"); par.age=30; par.height=1.80; return par; } void func3(PtrStuff par) { strcpy(par->job,"Programmer"); par->age=19; par->height=170; } int fun1(int age,int weight) { int temp=0; temp=age+weight; return temp; } void fun2(int age,int weight) { printf("your age is:%d\n",age); printf("your weight is:%d\n",weight); } |