Thanks guys. Okay this is what I have so far:
Code:
class IntStr
{
private:
typedef enum { INTEGER, STRING, UNION } MyType; //INTEGER, STRING, UNION are defined into MyType
MyType mTypeInfo; //mTypeInfo is declared as a MyType
union IntStrTag { //a union is declared
const char *mStr; //consisting of a pointer to a string
int mInt; //and an integer
} mIntStr; //the union is then named mIntStr
public:
//First constructor
IntStr ()
{
mTypeInfo = UNION;
}
//Second constructor
void SetInt (int init)
{
mTypeInfo = INTEGER;
mIntStr.mInt = init;
return ;
}
IntStr (int init)
{
SetInt (init);
}
//Third constructor
void SetString (const char *init)
{
mTypeInfo = STRING;
mIntStr.mStr = init;
return ;
}
IntStr (const char* init)
{
SetString (init);
}
//GetInt and GetString are defined
bool GetInt (int &retval)
{
if (mTypeInfo == INTEGER)
{
retval = mIntStr.mInt;
return false;
}
else if (mTypeInfo == STRING)
{
std::istringstream conv;
conv.str(mIntStr.mStr);
int temp;
conv >> temp;
if (conv)
{
SetInt (temp);
retval = mIntStr.mInt;
return false;
}
else { return true; }
}
else{ return true; }
}
bool GetString (const char *&retval)
{
if (mTypeInfo == STRING)
{
retval = mIntStr.mStr;
return false;
}
else if (mTypeInfo == INTEGER)
{
std::ostringstream conv;
conv << mIntStr.mInt;
if (conv)
{
SetString (conv.str().c_str());
retval = mIntStr.mStr;
return false;
}
else { return true; }
}
else { return true; }
}
// I/O friends are declared
friend istream& operator >> (istream &input , IntStr &intstr);
friend ostream& operator << (ostream &output , const IntStr &intstr);
};
istream& operator >> (istream &input , IntStr &intstr)
{
input >> intstr;
return input;
}
ostream& operator << (ostream &output , const IntStr &intstr)
{
output << intstr;
return output;
}
int main()
{
IntStr sample1_; //no error
IntStr sample2_; //no error
sample1_ = 123; //no error
sample2_ = "abc"; //no error
cout << sample1_ << endl; //run-time error here
cout << sample2_ << endl; //run-time error here
cin.get(); //pause to see console results
}
This compiles correctly.
I get a run-time error starting at 'cout'. I think I messed up the I/O again, but I made sure to add const on the ostream as Elysia pointed out.
To see if I understand: a union type contains enough memory for each type it unifies and can be treated as any type at any time?
If not, do I have to specify which part of the memory I want inside the union to be represented at runtime? Or is this handled inside of the class?
Sorry just trying to understand. If I have to specify it with .mInt or .mStr , then maybe I would have to include that information within the stream operator overloads right?
At least it compiles when the union type is defined as an int or a string, so that's good.
I just have to find a way to do I/O on the union class type.
I'm still learning but I'll study up on WhiteFlag's mention of public access methods.
Thanks guys