Accessing a variable in a union which is inside a class
Sorry for naive question in C++. For below code, there is a class, inside which there is a union declaration having two variables. How to access the variables in the union using the class object in code below:
class my
{
public:
//class member functions, and oeprator overloaded functions
public:
union uif
{
unsigned int i;
float f;
};
private:
//some class specific variables.
};
if there is an object of type my defined like
my v1;
开发者_高级运维in a function later
Using v1 how do i access float f; inside union above in code?
also I want to watch the value of this float f in the watch window of a debugger(VS-2010), how to do that?
I tried v1.uif.f , this gave error in the watch window as : Error oeprator needs class struct or union.
v1.
You are only defining the union within the scope of the class, not actually creating a member variable of its type. So, change your code to:
class my
{
public:
//class member functions, and oeprator (sic) overloaded functions
public:
union uif
{
unsigned int i;
float f;
} value;
private:
//some class specific variables.
};
Now you can set the member variables in your union member, as follows:
my m;
m.value.i=57;
// ...
m.value.f=123.45f;
You never actually defined any member of that union. You only ever defined the union itself. There is no spoon float.
You've only defined the type of the uniion, you've not yet declared an object of this union type.
Try this:
class my
{
public:
union uif
{
unsigned int i;
float f;
};
uif obj; //declare an object of type uif
};
my v;
v.obj.f = 10.0; //access the union member
One option I don't see already here is that of an Anonymous Union, which is where you have no type or instantiation. Like so:
class my
{
public:
//class member functions, and oeprator (sic) overloaded functions
function(int new_i) { i = new_i;}
function(float new_f) { f = new_f;}
public:
union /* uif */
{
unsigned int i;
float f;
};
private:
//some class specific variables.
};
my m;
m.i=57;
m.f=123.45f;
Remember that with unions, it is only defined to read from the last member variable written to.
You have defined your union in your class, but you haven't created an instance of it! Try:
union uif
{
unsigned int i;
float f;
} myUif;
And then use v1.myUif.f
(or i).
精彩评论