Basically, I have to overload the << operator for my tokenType struct, which follows as (cannot be changed, I have to use it this way)
struct tokenType
{
int category ; // one of token categories defined above
union
{
int operand ;
char symbol ; // '+' , '-' , '*' , '/' , '^' , '='
} ;
int precedence() const ;
}
My header for the overloading method is:
ostream & operator<< ( ostream & os , const tokenType & tk)
So, I need to print out the value in the struct tk, either an int or a char. How can I access what is contained within the union, when I don't know if the variable will be operand or symbol? Thanks.
What you would need to do is look at the category
member (which is not part of the union) to decide which of the union elements to use. Something like the following might be useful (I'm guessing at the category definitions, obviously):
switch (tk.category) {
case catOperand:
os << tk.operand;
break;
case catSymbol:
os << tk.symbol;
break;
}
Isn't that what the "category" number is supposed to indicate? This looks like a tagged union, where the category is the tag. It should tell you whether the token is an operand or a symbol, and you can use that to decide which field to access in the union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With