C++/Generic/Generic Class

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Generic Class: constructor

<source lang="cpp">

  1. include <iostream>

using namespace std; template <class X> class input {

 X data;

public:

 input(char *s, X min, X max);
 

}; template <class X> input<X>::input(char *s, X min, X max) {

 do {
   cout << s << ": ";
   cin >> data;
 } while( data < min || data > max);

} int main() {

 input<int> i("enter int", 0, 10);
 input<char> c("enter char", "A", "Z");
 return 0;

}


      </source>


Generic Class just for displaying the parameters

<source lang="cpp">

  1. include <iostream>
  2. include <fstream>

using namespace std; template <class CoordType> class MyClass {

 CoordType x, y;

public:

 MyClass(CoordType i, CoordType j) { 
    x = i; 
    y = j; 
 }
 void show() { 
    cout << x << ", " << y << endl; 
 }

}; int main() {

 MyClass<int> object1(1, 2), object2(3, 4);

 object1.show();
 object2.show();
 MyClass<double> object3(0.0, 0.23), object4(10.19, 3.098);
 object3.show();
 object4.show();
 return 0;

}


      </source>


Generic data types in a class definition.

<source lang="cpp">

  1. include <iostream>

using namespace std; template <class Type1, class Type2> class myclass {

 Type1 i;
 Type2 j;

public:

 myclass(Type1 a, Type2 b) { 
    i = a; 
    j = b; 
 }
 void show() { 
    cout << i << " " << j << "\n"; 
 }

}; int main() {

 myclass<int, double> object1(10, 0.23);
 myclass<char, char *> object2("X", "This is a test");
 object1.show(); // show int, double
 object2.show(); // show char, char *

 return 0;

}

      </source>