C Unions and Polymorphism [duplicate]

2019-03-31 07:37发布

问题:

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?

回答1:

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).



回答2:

You have to use explicit type conversion:

A myA;
myMethod((C) myA);


回答3:

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.