![]() |
![]() |
![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
![]() |
![]() |
[an error occurred while processing this directive]
Steps
How It Works Listing 6.1 shows how the class is defined to accept any simple data type. The constructor and single member function are also type independent. In the main body of the program, three instances of the generic template class are created. The first object, x, has its member variable data created as type integer. The second object, y, is created using type char and the third object, z, is created using type double. The program simply shows how the single template class can be configured to deal with any simple data type. Listing 6.1 A Single Class Template with a Simple Member Variable; Three Objects Are Created, Each Using a Different Data Type // Template using simple data types. // T is used to specify unknown data type. #include <iostream.h> template <class T> class TSimple { private: T data; public: TSimple(T n); void Show(); }; template <class T> TSimple<T>::TSimple(T n) { data = n; } template <class T> void TSimple<T>::Show() { cout << data << endl; } main() { TSimple<int> x(25); x.Show(); TSimple<char> y(P); y.Show(); TSimple<double> z(1.25); z.Show(); return(0); } The screen output should look something like this: 25 P 1.25 Comments Try changing the code to use other simple data types such as float and see how flexible the template class can be. 6.2 Create a template class to represent any simple data type and extend it to read in data to a variable of any data type?Problem The problem here is very similar to that described in the previous How-To. This time however, rather than storing and displaying static data, you are reading in some data from the keyboard. You do not know what that data type is initially, but you can set up a template class that can be customized to handle any simple C++ data type. Technique The technique is virtually identical to the technique introduced in the previous How-To. All you need to do is add a member function to your template class that asks the user to enter some data. This new member function is set up to handle any simple data type. Within the main program when you create an object based upon the class, instruct the class to handle a simple data type such as an integer or character. After that has been done, all data types represented by T become an integer or character. Steps
main() { TSimple<int> x; x.Gather(); x.Show(); return(0); }
|
![]() |
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.
|