Question: Create a Template Numbers Class The typedef approach is great because we only have to change one line to change a class from using int
Create a Template Numbers Class
The typedef approach is great because we only have to change one line to change a class from using "int" data to using "float" data. The problem is that we can not easily have a main program that works with BOTH kinds of classes at the same time. This is why templates were added to C By using a template class, we can supply the data type we want to use when we declare the objects in the main program.
Start by making a backup copy of the typedef version of "numbers.cpp so you do not lose this work. Next, edit the class definition to remove the typedef line and add the following "template just above the class definition. Do NOT put an ; after this line or you will get a million syntax errors.
Next, copypaste this line just before each of your method definitions to tell the compiler that these methods are templated. Then change the "Numbers::" to be "Numbers::" in each of the method headers. When you are finished, your methods should all look like this:
template
int Numbers::getCount
return Count;
Next, replace the original main program with the following code and compile and run your program. If you look at this code, you will see that we used "Numbers num;" to declare a "num" object that reads and processes the data using "int" data. We used "Numbers num; to declare the "num object which is used to read and process the data using "float" data.
For templates we MUST compile the numbers.h and numbers.cpp code
at the same time as main.cpp in order for the compiler to resolve
what data types you are using in Numbers objects. This is done
by including "numbers.cpp below.
When compiling on the Linux command line use gWall main.cpp
When compiling using an IDE, you may need to rename "numbers.cpp
to "numbers.cpptxt and change the include line below accordingly
If you do not rename the file, it may be compiled twice causing
a large number of confusing errors.
#include "numbers.cpp
int main
string filename;
cout "Enter filename:";
cin filename;
Process int numbers
Numbers num;
num.readFilefilename;
cout "min num.findMin endl;
cout "max num.findMax endl;
cout "mean num.findMean endl;
Process float numbers
Numbers num;
numreadFilefilename;
cout "min numfindMin endl;
cout "max numfindMax endl;
cout "mean numfindMean endl;
Finally, edit your program and see what happens when you use the following data types short long, double, char, string when creating Numbers objects. Which work fine? Which have problems?
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
