Breaker Posted January 5, 2015 Share Posted January 5, 2015 (edited) I will give you a basic understanding of templates (the features we will use) as this tutorial progresses, don't worry if you don't completely understand it, it should be simple. Okay, so let me just throw some code at you before I break it down. Here is our basic class definition: Code: This is the hidden content, please Sign In or Sign Up Alright. Line by line breakdown: go Code: This is the hidden content, please Sign In or Sign Up this defines myStack as a template class Well, what does that mean? It means that the class can take a number of different forms, and we just create a template for it to do so. When we define our stack, we can specify what type we want to put in, for example: int float char even myStack classes! and just about EVERYTHING else that stores data well, what does this mean? Code: This is the hidden content, please Sign In or Sign Up That simply defines a type that we can use to write our class. Every instance of custom_type is replaced at compile time with whatever type we want to use for that specific instance. For those of you who know C, consider it a #define, except we can redefine what it means without a bunch of hacky garbage. There really isn't a whole lot more after that, except this function has changed: Code: This is the hidden content, please Sign In or Sign Up Why did we add the & in there? Simple: because we aren't dealing with built-in types. ALL ABSTRACT TYPES MUST BE PASSED BY REFERENCE, per C++ spec. This won't affect our code at all. Actually, it will be almost IDENTICAL to the last C++ stack tutorial. This will be commented. Here is the whole thing: oh wait! forgot to say one thing Since this is a template class, all of the code MUST be in the header file (and I ABSOLUTELY hate this), so I will make it REALLY simple, and even put it inside the class definition. Code: This is the hidden content, please Sign In or Sign Up Now, that was VERY simple. I did not go into the drawn out version of the functions, you can find those in the "creating a C++ stack class" link/tutorial at the top of this thread. USING it, however is NOT as simple. If you are new to templates/have never seen them before, this may come difficult to you (because we don't have a whole lot to work off of here) but I will try and help. Code: This is the hidden content, please Sign In or Sign Up So, there you have it! Compile it and run it. Output should look like so: Code: This is the hidden content, please Sign In or Sign Up Who wants to see one that we can do this: Code: This is the hidden content, please Sign In or Sign Up Leave a comment if you want to see how to make variable type stacks (thats what REAL system stacks are) Edited January 5, 2015 by you2004975 Wrap Code Tags Link to comment Share on other sites More sharing options...
Recommended Posts