How can I create my own var type?
Printable View
How can I create my own var type?
Classes or struct's
The tutorials has info on both.
don't forget enumerations
Okay, but how can I make one like this:
Instead of like this:Code:MyVarName MyVar = 980;
Code:MyVarName MyVar;
MyVar.StructPart = 980;
how about a template (I'm not too enlightened on them, so others will have to answer questions about them)
Code:template <class T>
class MyVarName
{
public:
MyVarName() {}
MyVarName(const T& a) {data = a;}
void operator=(const T& a) {data = a;}
private:
T data;
};
int main()
{
MyVarName<int> MyVar1 = 123;
MyVarName<std::string> MyVar2 = "Hello";
return 0;
}
Well, classes are more powerful, and you could have multiple types of data in them, you would overload the = operator. But if you just want to say take a predefined type such as double and call it what you want (for whatever reason) just typedef it.
Code:#include <iostream>
using namespace std;
typedef int My_Int;
typedef double My_Double;
int main ()
{
My_Int var_name_int; //Declares a variable of type My_int (which is just int)
My_Double var_name_double;
My_Int my_array[2];
var_name_int = 5;
cout << var_name_int << endl;
var_name_double = 5.55;
cout << var_name_double << endl;
my_array[0] = 55;
my_array[1] = 555;
cout << my_array[0] + my_array[1] << endl;
system("PAUSE");
return 0;
}
With typedef you can't really create a new type, but you can create a new name for an existing type. The following is quite common:
Code:typedef unsigned long ULONG; // Define a "new" type called ULONG
ULONG x = 3; // Define a new variable x, of type ULONG
ULONG y = 4; // Define a new variable y, of type ULONG
Thanks guys, thats what was looking for.