typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}order;
typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}cake;如何使类型胡枝子结构的内容成为一体?我可以用information.order.name_cake调用这个命令
information.cake.name_cake
为了简单而不浪费语言,谢谢
发布于 2022-05-15 13:44:51
我建议在蛋糕和订单中使用相同的结构,在c中没有多态性。
发布于 2022-05-15 14:15:53
以您喜欢的方式访问它们:
#include <stdio.h>
typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}order;
typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}cake;
typedef struct {
union {
order the_order;
cake the_cake;
}; // anonymous union
}information;
int main() {
order an_order = {"cakename", "code", 0, "about", "taste"};
information info = *((information*)&an_order);
printf("From order: %s\n", info.the_order.name_cake);
printf("From cake: %s\n", info.the_cake.name_cake);
return 0;
}$ gcc -Wall ordercake.c
$ ./a.out
From order: cakename
From cake: cakename
$ 一般来说,您希望用C语言进行面向对象的编程。因此,请看一看:How can I simulate OO-style polymorphism in C? (甚至有一本免费的书,可作为pdf链接到如何实现它)。
现在是一个结构体的例子:
#include <stdio.h>
typedef struct{
char name_cake[10];
char code_cake[10];
}cake;
typedef struct{
cake the_cake; // the common part
char cake_extension[10]; // the new part, order is important
}extended_cake;
int main() {
extended_cake an_extended_cake = {{"cakename", "code"}, "extension"};
// now treat it as a cake
cake *a_normal_cake = (cake *)&an_extended_cake;
printf("From cake: %s\n", a_normal_cake->name_cake);
return 0;
}$ gcc -Wall ordercake.c
$ ./a.out
From cake: cakename
$ 发布于 2022-05-17 21:11:23
不确定您要做什么,但是您可以简单地嵌套这样的结构:
struct foo {
order order;
cake cake;
}如果您希望订单和蛋糕的内容占用相同的内存空间,您应该使用匿名联合,如上面所写。
https://stackoverflow.com/questions/72248769
复制相似问题