cpp:class_templates
This is an old revision of the document!
Templates κλάσεων
Σε αναλογία με τα templates συναρτήσεων μπορούμε να κατασκευάσουμε κλάσεις που να λαμβάνουν ως παράμετρο ένα ή περισσότερους τύπους δεδομένων. Στο παρακάτω παράδειγμα, έχουμε την κλάση Box<T> η οποία είναι παραμετρική.
- Box.hpp
template <typename T> class Box { T e; public: Box(T e); T get() const; void set(T e); template <typename U> friend std::ostream& operator<<(std::ostream& out, const Box<U>& t); }; template <typename T> Box<T>::Box(T e) { this->e = e; } template <typename T> T Box<T>::get() const { return e; } template <typename T> void Box<T>::set(T e) { this->e = e; } template <typename T> std::ostream& operator<<(std::ostream& out, const Box<T>& t) { out << t.get(); return out; }
H παραπάνω κλάση μπορεί να παράγει διαφορετικούς τύπους δεδομένων, ανάλογα με τον τύπο T. Στο παρακάτω παράδειγμα έχουμε ένα μία κλάση Box<int>, μία κλάση Box<double> και μία κλάση Box<Student>.
- BoxUsage.cpp
#include "Box.hpp" #include "Student.hpp" using namespace std; int main() { Box<int> b(15); Box<double> d(4.23); Student george = {"George", 1234}; Box<Student> studentBox(george);
cpp/class_templates.1556894427.txt.gz · Last modified: 2019/05/03 13:40 (external edit)