Howdy~
I just found when I want to initialize variables inside a union or struct compiler will report an error, why couldnt we do that ???
Howdy~
I just found when I want to initialize variables inside a union or struct compiler will report an error, why couldnt we do that ???
Never end on learning~
Either declare the members static (remember, unions can't have static members) or, create an object of the particular struct/union and initilize those variables.
Some code would help too.
thanx. but I wonder why we couldnt initialize variable just as class ?Originally posted by Eibro
Either declare the members static (remember, unions can't have static members) or, create an object of the particular struct/union and initilize those variables.
Some code would help too.
Never end on learning~
You can, but maybe not in a constructor as you may be thinking.
Post some code.
for example:Originally posted by Eibro
You can, but maybe not in a constructor as you may be thinking.
Post some code.
if we run this code will get an error, why couldnt we do that ???Code:union myUnion { int a=0; bool b; char c; }
Last edited by black; 11-11-2002 at 01:33 AM.
Never end on learning~
You can specify a union constructor as you would with a struct or class....do so and set the member with the largest varible type to zero.
Code:#include <iostream> union myUnion { myUnion():a(0){} int a; bool b; char c; }; int main() { myUnion u; std::cout << "As int " << u.a << std::endl; std::cout << "As bool " << u.b << std::endl; std::cout << "As char " << u.c << std::endl; }