gpt4 book ai didi

c++ - 使用 C++ union ,当你想要的成员未知时

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:02:44 25 4
gpt4 key购买 nike

基本上,我必须为我的 tokenType 结构重载 << 运算符,如下所示(无法更改,我必须以这种方式使用它)

struct tokenType 
{
int category ; // one of token categories defined above
union
{
int operand ;
char symbol ; // '+' , '-' , '*' , '/' , '^' , '='
} ;
int precedence() const ;
}

我的重载方法的标题是:

ostream & operator<< ( ostream & os , const tokenType & tk)

因此,我需要打印出 struct tk 中的值,int 或 char。当我不知道变量是操作数还是符号时,如何访问 union 中包含的内容?谢谢。

最佳答案

您需要做的是查看 category 成员(它不是 union 的一部分)来决定使用哪个 union 元素。像下面这样的东西可能会有用(显然我在猜测类别定义):

switch (tk.category) {
case catOperand:
os << tk.operand;
break;
case catSymbol:
os << tk.symbol;
break;
}

关于c++ - 使用 C++ union ,当你想要的成员未知时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com