This is a sample program that teaches us unions & structs. Structs are public access-specifiers by default, so why do I need :: the scope resolution operator when referring to the enum & not the union within the struct?
myData2.value.alphabet = 'x'; //This is OK, no :: needed
myData1.Type = ComplexType::Int;//Why :: needed & not just "...ComplexType.Int;"
//myData1.Type = myData1.DataType::Int;//works too, why not myData1.DataType.Int
//myData1.Type = myData1.DataType.Int; //Does not work, why?
Many cases where sometimes () are needed & other times just use "." instead of :: it just ends up confusing. I have to find more examples from previous sample programs.
//On another note why is this "()" needed in this class pointer?
MyClass* MyClass1 = new MyClass();
//It is a class, why () needed? I understand [] needed for array pointers, but this is a class?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include <iostream>
using namespace std;
struct ComplexType
{
enum DataType
{
Int,
Char
} Type;
union Value
{
int num;
char alphabet;
Value(){}
~Value(){}
} value;
};
void DisplayComplexType (const ComplexType& obj)
{
switch (obj.Type)
{
//case obj.DataType::Int: //works too
case ComplexType::Int:
cout << "num = " << obj.value.num << endl;
break;
case ComplexType::Char:
cout << "Char =" << obj.value.alphabet << endl;
break;
}
}
int main()
{
ComplexType myData1, myData2;
//myData1.Type = myData1.DataType::Int; //works too
myData1.Type = ComplexType::Int;
myData1.value.num = 2017;
myData2.Type = ComplexType::Char;
myData2.value.alphabet = 'x';
DisplayComplexType (myData1);
DisplayComplexType (myData2);
return 0;
}
|