C++ 模板應用示例

#include<iostream>
  using namespace std;
  class person
  {
   int age;
  public:
   person(int a)
   {
   age=a;
   }
   person & operator +(const person &p1)
   {
   age=age+p1.age;
   return *this;
   }
   void ShowAge()
   {
   cout << "age=" << age << endl;
   }
  };
  template<class T,class N,class M> T GetRes(T a,N b,M c)
  {
   cout << "a type is:" << typeid(a).name() << endl;
   cout << "b type is:" << typeid(b).name() << endl;
   cout << "c type is:" << typeid(c).name() << endl;
   return a+(T)b;
  }
  template<class T,class N> T GetRes(T a,N b)
  {
   cout << "a type is:" << typeid(a).name() << endl;
   cout << "b type is:" << typeid(b).name() << endl;
  }
  template<class T,class N> T GetRes(N b,T a)
  {
   cout << "a type is:" << typeid(a).name() << endl;
   cout << "b type is:" << typeid(b).name() << endl;
  }
  
  int main()
  {
   person p1(10),p2(2),p3(3);
   person p4=GetRes(p1,p2,p3);
   cout << GetRes(1000,2000,3000.4567) << endl;
   p4.ShowAge ();
  
   return 0;
  }  
發佈了71 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章