现在的位置: 首页 > 综合 > 正文

C++ 模板应用示例

2014年01月02日 ⁄ 综合 ⁄ 共 828字 ⁄ 字号 评论关闭
#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;
  }  

抱歉!评论已关闭.