rfm*_*as3 4 c++ operator-overloading ostream unions
基本上,我必须为我的tokenType结构重载<<运算符,后面跟着(不能更改,我必须以这种方式使用它)
struct tokenType
{
int category ; // one of token categories defined above
union
{
int operand ;
char symbol ; // '+' , '-' , '*' , '/' , '^' , '='
} ;
int precedence() const ;
}
Run Code Online (Sandbox Code Playgroud)
我的重载方法的标题是:
ostream & operator<< ( ostream & os , const tokenType & tk)
Run Code Online (Sandbox Code Playgroud)
所以,我需要打印出struct tk中的值,int或char.当我不知道变量是操作数还是符号时,如何访问union中包含的内容?谢谢.
您需要做的是查看category
成员(不是联合的一部分)来决定使用哪个联合元素.像下面这样的东西可能有用(我猜测类别定义,显然):
switch (tk.category) {
case catOperand:
os << tk.operand;
break;
case catSymbol:
os << tk.symbol;
break;
}
Run Code Online (Sandbox Code Playgroud)