Source of testOrderedPair.cpp


  1: //testOrderedPair.cpp
  2: //Illustrates a template class.

  4: #include <iostream>
  5: #include <string>
  6: using namespace std;


  9: template<typename T>
 10: class OrderedPair
 11: {
 12: public:
 13:     OrderedPair() { first = T(); second = T(); }
 14:     OrderedPair
 15:     (
 16:         T first, //in
 17:         T second //in
 18:     )
 19:     {
 20:         this->first = first;
 21:         this->second = second;
 22:     }
 23:     void SetFirst(T first)   { this->first = first;   }
 24:     void SetSecond(T second) { this->second = second; }
 25:     T getFirst()  { return first;  }
 26:     T getSecond() { return second; }
 27:     void display() { cout << "(" << first << ", " << second << ")"; }

 29: private:
 30:     T first;
 31:     T second;
 32: };


 35: int main()
 36: {
 37:     OrderedPair<int> p_int1;
 38:     OrderedPair<int> p_int2(7, 34);

 40:     cout << "\nHere are two ordered pairs of integers, the default "
 41:             "ordered pair,\nand another ordered pair:\n";
 42:     p_int1.display();  cout << endl;
 43:     p_int2.display();  cout << endl;
 44:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 46:     p_int1.SetFirst(12);
 47:     p_int1.SetSecond(30);
 48:     cout << "The default ordered pair of integers has now been "
 49:          << "altered.\nThe first component now contains "
 50:          << p_int1.getFirst()
 51:          << ", and the second component now contains "
 52:          << p_int1.getSecond() << ".\n";
 53:     cout << "And here are the altered values displayed as an "
 54:             "ordered pair:\n";
 55:     p_int1.display();  cout << endl;
 56:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 58:     cout << "\nFinally, here are two ordered pairs of strings, the "
 59:             "default ordered pair,\nand another ordered pair:\n";
 60:     OrderedPair<string> p_string1;
 61:     OrderedPair<string> p_string2("George", "Dick");
 62:     p_string1.display();  cout << endl;
 63:     p_string2.display();  cout << endl;
 64:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 65: }