我有结构(A),它需要另一个结构(B)作为成员。 现在我想要结构 C 作为 A 的成员而不是 B。 B和C都是同一类型
typedef struct
{
int a;
B b;
}A
typedef struct
{
int a;
}B
typedef struct
{
int a;
}C
如何将结构 C 指定为成员而不是 B。如何进行类型转换 请帮忙
最佳答案
在不知道为什么要这样做的情况下,很难推荐策略。不过,这里有一些选项。
选项 1:使用模板。 (仅限 C++)
template <type T>
struct A
{
int a;
T* t;
};
struct Foo
{
int a;
};
struct B : public Foo
{
};
struct C : public Foo
{
};
struct A<Foo> A_foo;
struct B;
struct C;
A_foo.t = &B; //OK! This can now take pointer to any class that extends Foo.
A_foo.t = &C; //OK!
选项 2:使结构 A 包含一个 void*(不推荐,您将失去所有类型安全性)。 (C/C++)
struct A
{
int a;
void* foo; // you can now assign any pointer to foo :-S
};
关于c++ - 型铸结构件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4452303/