I need to have several instances of 开发者_开发问答a union as class variables, so how can I create a union instance in the heap? thank you
The same as creating any other object:
union MyUnion
{
unsigned char charValue[5];
unsigned int intValue;
};
MyUnion *myUnion = new MyUnion;
Your union is now on the heap. Note that a union is the size of it's largest data member.
My C++ is a bit rusty, but:
my_union_type *my_union = new my_union_type;
...
delete my_union;
Use the new
operator.
I'm not sure where you want to head with this. A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. So starting from this, if you have a union defined like this:
union DataType
{
char ch;
integer i;
float f;
double d;
};
You can then use DataType
as a type to define members in a class or as a type to define variables on the stack, just like regular types, struct or classes you define.
Use the new
operator:
#include <iostream>
union u {
int a;
char b;
float c;
};
class c {
public:
c() { u1 = new u; u2 = new u; u3 = new u; }
~c() { delete u1; delete u2; delete u3; }
u *u1;
u *u2;
u *u3;
};
int main()
{
c *p = new c;
p->u1->a = 1;
p->u2->b = '0' + 2;
p->u3->c = 3.3;
std::cout << p->u1->a << '\n'
<< p->u2->b << '\n'
<< p->u3->c << std::endl;
delete c;
return 0;
}
Same as a struct :) You can use malloc()
and do it the C way, or new
for the C++ way. The secret is that structs, unions and classes are related; a struct is just a class (usually) without methods. There's more clarification in the following comments, should you care.
精彩评论