我有一个模板联合类型 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;
}
可能是什么问题?在此先感谢您的时间。