110 likes | 212 Views
Class Template. A class template is a pattern for the compiler to use to build a class definition. Since the compiler generates the class definition the template must be made visible. This is done by including the implementation file in the header file. Class Template.
E N D
Class Template A class template is a pattern for the compiler to use to build a class definition. Since the compiler generates the class definition the template must be made visible. This is done by including the implementation file in the header file.
Class Template template <class Item> class myClass { // class members };
Class Template template <class T> class myClass { public: myClass(); void setData(const T&) T getData() const; private: T myData; };
Class Template template <class T> void myClass<T>::setData(const T& inData) { myData = inData; } template <class T> T myClass<T>::getData() { return myData; }
Class Template A class template is a model for the compiler to use to build a class definition. Since the compiler generates the class definition the template must be made visible. This is done by including the implementation file in the header file.
Class Template (myClass.h) template <class Item> class myClass { // class member }; #include “myClass.cpp”
Class Template myClass<int> anInt; myClass<float> aFloat; myClass<CString> aCString; anInt.setData(2); cout << anInt.getData() << endl; aFloat.setData(3.14); cout << aFloat.getData() << endl; aCString.setData(“test string”); cout << aCString.getData() << endl;
#include <iostream.h> #include "afx.h" // for MFC CString #include "myClass.h” int main() { myClass<int> anInt; myClass<double> aFloat; myClass<CString> aCString; anInt.setData(2); cout << anInt.getData() << endl; aFloat.setData(3.14); cout << aFloat.getData() << endl; aCString.setData("test string"); cout << aCString.getData() << endl; return 0; }
#include <iostream.h> #include "afx.h" // for MFC CString #include "myClass.h” int main() { myClass<int> anInt; myClass<double> aFloat; myClass<CString> aCString; anInt.setData(2); cout << anInt.getData() << endl; aFloat.setData(3.14); cout << aFloat.getData() << endl; aCString.setData("test string"); cout << aCString.getData() << endl; return 0; }
/* Screen capture of output 2 3.14 test string Press any key to continue */
Class Template We can now use the template to generalize the List ADT.