How can I create my own var type?
How can I create my own var type?
Classes or struct's
The tutorials has info on both.
don't forget enumerations
If any part of my post is incorrect, please correct me.
This post is not guarantied to be correct, and is not to be taken as a matter of fact, but of opinion or a guess, unless otherwise noted.
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; }
Last edited by Ancient Dragon; 11-03-2005 at 04:11 PM.
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
Last edited by DougDbug; 11-03-2005 at 04:58 PM.