C Unions and Polymorphism [duplicate]

2019-03-31 07:41发布

Possible Duplicate:
How can I simulate OO-style polymorphism in C?

I'm trying to use unions to create polymorphism in C. I do the following.

typedef struct{
...
...
} A;

typedef struct{
...
... 
} B;

typedef union{
        A a;
        B b;
}C;

My question is: how can I have a method that takes type C, but allows for A and B's also. I want the following to work:

If I define a function:

myMethod(C){
...
}

then, I want this to work:

main(){
A myA;
myMethod(myA);
}

It doesn't. Any suggestions?

3条回答
手持菜刀,她持情操
2楼-- · 2019-03-31 07:56

You have to use explicit type conversion:

A myA;
myMethod((C) myA);
查看更多
姐就是有狂的资本
3楼-- · 2019-03-31 08:02

The short answer is that in C, you can't.

In C++, you could overload myFunction() and provide several implementations.

In C, you can only have a single myFunction(). Even if you could declare the function so that it could take A, B or C (e.g. as void*), it would have no way of knowing which of the three it has been supplied with.

查看更多
冷血范
4楼-- · 2019-03-31 08:19

GNU and IBM support the transparent_union extension:

typedef union __attribute__((transparent_union)) {
        A a;
        B b;
} C;

and then you can use As or Bs or Cs transparently:

A foo1;
B foo2;
C foo3;
myMethod(foo1);
myMethod(foo2);
myMethod(foo3);

See The transparent_union type attribute (C only).

查看更多
登录 后发表回答