C++ union 字段设置不正确

标签 c++ unions unassigned-variable

我有一个模板化 union 类型 NodeType。 问题在于,在分配其变量字段时未正确设置,并且在随后访问时包含垃圾值。具体来说,问题出现在 _field1 和 _field2 - 请参阅主要内容。

#include <cstdlib>
#include <iostream>

using namespace std;


        template <class T>
        struct structExampleType                
        {
          T _structField;
          typedef structExampleType<T>* pointerStructExample;
        };


         enum TYPE_tag
         {FIELD1_tag, FIELD2_tag} TYPE_tag; 

          template <class T>//, class P>
          union NodeType
          {
           enum TYPE_tag _nodeType_tag;
           char _field1;
           typename structExampleType<T>::pointerStructExample _field2;

           NodeType(){_field2=0;}

           NodeType(enum TYPE_tag nodeType_tag, char _charField)
           {
            _nodeType_tag=nodeType_tag;
            _field1=_charField;
            //_field2=0;
           }  

           NodeType(enum TYPE_tag nodeType_tag, typename structExampleType<T>::pointerStructExample pointer)
           {
            _nodeType_tag=nodeType_tag;
            _field2=pointer;
            //_field1='-';
           }          

          };







int main(int argc, char *argv[])
{
    NodeType<int> node1, node2;
    structExampleType<int>* structExamplePointer;

    structExamplePointer=new structExampleType<int>();

    structExamplePointer->_structField=100;
//    structExamplePointer->_field2=structExamplePointer;

    node1=NodeType<int>(FIELD1_tag,'-');
    node2=NodeType<int>(FIELD2_tag,structExamplePointer);    


    cout<<endl<<"node1: ";    
    if (node1._nodeType_tag==FIELD1_tag)
    {cout<<node1._field1<<endl;}
    else
    {cout<<node1._field2<<endl;}        


    cout<<endl<<"node2: ";
    if (node2._nodeType_tag==FIELD2_tag)
    {cout<<node2._field1<<endl;}
    else
    {
        cout<<node2._field2<<endl;
        cout<<(node2._field2)->_structField<<endl;
    }  



    system("PAUSE");
    return EXIT_SUCCESS;
}

可能是什么问题?提前感谢您的宝贵时间。

最佳答案

main 中有这两行:

structExampleType<int>* structExamplePointer;

structExamplePointer->_structField=100;

请记住,除非局部变量具有默认构造函数(指针没有),否则它们不会被初始化,因此在第二个你取消引用未初始化的指针 structExamplePointer,导致未定义的行为。

您似乎还误解了 union 的用途,因为您试图设置多个字段。在 union 中,所有字段共享 相同的空间,因此当写入一个成员时,所有成员都会更改。只有最后写入成员才有效。尝试使用其他字段可能会再次导致未定义的行为。


如果您需要一个“标签”字段其他数据,您应该选择包含标签和 union 数据的结构:

struct NodeType
{
    enum TAG_Type
    {
        FIELD1,
        FIELD2
    } type;

    union
    {
        char field1;
        struct some_struct* field2;
    }
};

关于C++ union 字段设置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18248162/

相关文章:

C++ 访问 union 结构中的变量

c - memcpy to union 没有按预期工作

symfony - elasticsearch返回 “Unassigned”

c++ - Qt 设计器 : Changing the base class of a window

c# - C++ 到 C# worker 类(Class)的 union

c++ - 显式加载库的干净方法

c#开关问题

javascript - 在 for 循环中时,Jquery 赋值失败

c++ - 得到一个奇怪的 int 值

c++ - 为字符串文字 C++ 引发编译器错误的宏