C++

pairs.h

  1. #ifndef PRO1_PAIRS_H
  2. #define PRO1_PAIRS_H
  3. #include <iostream>
  4. #include <string>
  5. using namespace std;
  6. template <class T1, class T2>
  7. class Pair {
  8. private:
  9. T1 a;
  10. T2 b;
  11. public:
  12. T1 & first();
  13. T2 & second();
  14. T1 first() const { return a; }
  15. T2 second() const { return b; }
  16. Pair(const T1 & aval, const T2 & bval) : a(aval), b(bval){}
  17. Pair(){}
  18. };
  19. template <class T1, class T2>
  20. T1& Pair<T1, T2>::first() {
  21. return a;
  22. }
  23. template <class T1, class T2>
  24. T2& Pair<T1, T2>::second() {
  25. return b;
  26. }
  27. #endif //PRO1_PAIRS_H

pairs.cpp

  1. #include "pairs.h"

main.cpp

  1. #include <iostream>
  2. #include "module11_class_template/multiple_type_parameters/pairs.h"
  3. using namespace std;
  4. // 多个类型参数
  5. void useMultipleTypeParameter(){
  6. Pair<string, int> rating[4] = {
  7. Pair<string, int>("The Purple Duke", 5),
  8. Pair<string, int>("Jake's Frisco AI Fresco", 4),
  9. Pair<string, int>("Mont Souffle", 5),
  10. Pair<string, int>("Gertie's Eats", 3)
  11. };
  12. int joints = sizeof(rating) / sizeof(Pair<string, int>);
  13. cout << "Rating :\t Eatery\n";
  14. for (int i = 0; i < joints; i++) {
  15. cout << rating[i].second() << ":\t" << rating[i].first() << endl;
  16. cout << "Oops! Revised rating :\n";
  17. rating[3].first() = "Gertie's Fab Eat";
  18. rating[3].second() = 6;
  19. cout << rating[3].second() << ":\t" << rating[3].first() << endl;
  20. }
  21. }
  22. int main() {
  23. useMultipleTypeParameter();
  24. return 0;
  25. }