今天介绍一种结构体赋值的新方法,适用于你想赋值部分成员时的情况
通常情况下
struct animal dog = {“dog”,1,1,1};
struct Animal person={
.peat = personEat,
.pbeat = personBeat,
};
dem代码展示
#include <stdio.h>
struct Animal
{
char name[128];
int age;
int sex;
void (*peat)();
void (*pbeat)();
};
void dogEat()
{
printf("dog eat\n");
}
void catEat()
{
printf("cat eat\n");
}
void personEat()
{
printf("person eat\n");
}
void dogBeat()
{
printf("dog beat\n");
}
void catBeat()
{
printf("cat beat\n");
}
void personBeat()
{
printf("person beat\n");
}
int main()
{
struct Animal dog= {
.peat = dogEat,
.pbeat = dogBeat,
};
struct Animal cat ={
.peat = catEat,
.pbeat = catBeat,
};
struct Animal person={
.peat = personEat,
.pbeat = personBeat,
};
/* struct Animal dog = {"dog",1,1,1,1,1} */
/*
dog.peat = dogEat;
cat.peat = catEat;
person.peat = personEat;*/
dog.peat();
cat.peat();
person.peat();
dog.pbeat();
cat.pbeat();
person.pbeat();
/* code */
return 0;
}