【发布时间】:2013-08-15 07:33:32
【问题描述】:
我有一个模板联合类型 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;
}
可能是什么问题?提前感谢您的宝贵时间。
【问题讨论】:
-
您正在使用未初始化的指针。我根本不明白为什么需要指针。
标签: c++ unions unassigned-variable