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

标签 c++ operator-overloading unions ostream

基本上,我必须为我的 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/

相关文章:

iphone - 检测多个按钮被单击的最佳方法是什么

c++ - python 与 c++ 使用 ctypes

c++ - 检查 OpenCV 矩阵是否为浮点分量类型

c++ - 请在C++中解释char *返回类型

Typescript 有联合,那么枚举是多余的吗?

c++ - 使用友元运算符<<的编译器错误

ios - 如何在swift中重载赋值运算符

python - 你如何在 python 中重载插入符号 (^) 运算符

c - 两个 union 的算术,未定义的行为?

C : assign value to uninitialzed struct and union