gpt4 book ai didi

c - 根据类型区分结构

转载 作者:行者123 更新时间:2023-12-03 03:43:49 26 4
gpt4 key购买 nike

我有两个不同的结构,带有类型字段定义(请参见下文)。

struct A {
int type;
char type_a[8];
char random[8];
};


struct B {
int type;
char type_b[16];
char random[16];
};

现在我想根据类型来区分这两种结构,例如

if (type == A)
struct A *a = (struct A *)buff;
if (type == B)
struct B *b = (struct B *)buff;

我不知道之前在 buff 中传递给我的是什么类型的结构。那么我如何从 buff 中提取类型。类型字段保证是两个结构中的第一个字段。

最佳答案

您可以使用 C 语言中的 OOP 设计模式来完成此类操作。

这里的想法是Base结构有一个type成员。结构AB“扩展”Base。由于 Base 结构是 AB 的第一个成员,因此任何一个都可以转换为 Base 并使用就这样。

这将为您提供一种在 BaseAB 之间进行转换的安全方法,同时在您使用时提供编译时类型安全性只需使用 Base 的实例即可。

typedef struct Base {
int type;
} Base;

typedef struct A {
Base base;
} A;

typedef struct B {
Base base;
} B;

int ATYPE = 1;
int BTYPE = 2;

int getType(Base *base) {
return base->type;
}

int _tmain(int argc, _TCHAR* argv[])
{
A a;
B b;
B *bptr;
Base *base;
int baseType;

a.base.type = ATYPE;
b.base.type = BTYPE;

base = (Base*)&b;

baseType = getType(base);

// something like this is reasonable,
// since you know that base is an
// instance of B.
if (baseType == BTYPE) {
bptr = (B*)base;
}

if (baseType != BTYPE) return -1;
return 0;
}

关于c - 根据类型区分结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com