結構體的新玩法

zj17783254632發表於2021-01-05
#include <stdio.h>
struct Animal
{
	char name;
	int age;
	int sex;
	void (*beat)();
	void (*eat)();
};

void catbeat()
{
	printf("zhua\n");
}

void dogbeat()
{
	printf("yao\n");
}

void personbeat()
{
	printf("ti\n");
}

void cateat()
{
	printf("eat fish\n");
}

void dogeat()
{
	printf("eat gutou\n");
}

void personeat()
{
	printf("eat rice\n");
}

int main()
{
	struct Animal cat;
	struct Animal dog;
	struct Animal person;
	
	cat.beat = catbeat;
	cat.eat = cateat;
	cat.beat();
	cat.eat();

	dog.beat = dogbeat;
	dog.eat = dogeat;
	dog.beat();
	dog.eat();

	person.beat = personbeat;
	person.eat = personeat;
	person.beat();
	person.eat();
}

#include <stdio.h>
struct Animal
{
	char name;
	int age;
	int sex;
	void (*beat)();
	void (*eat)();
};

void catbeat()
{
	printf("zhua\n");
}

void dogbeat()
{
	printf("yao\n");
}

void personbeat()
{
	printf("ti\n");
}

void cateat()
{
	printf("eat fish\n");
}

void dogeat()
{
	printf("eat gutou\n");
}

void personeat()
{
	printf("eat rice\n");
}

int main()
{
	struct Animal cat = {
		.beat = catbeat,
		.eat =  cateat
	};

	struct Animal dog = {
		.beat = dogbeat,
		.eat =  cateat
	};

	struct Animal person = {
		.beat = personbeat,
		.eat  = personeat
	};
	
	cat.beat();
	cat.eat();

	dog.beat();
	dog.eat();

	person.beat();
	person.eat();
}

相關文章