C++ template学习二 类模板定义及实例化

一个类模板(也称为类属类或类生成类)允许用户为类定义一种模式,使得类中的某些数据成员、默写成员函数的参数、某些成员函数的返回值,能够取任意类型(包括系统预定义的和用户自定义的)。
如果一个类中数据成员的数据类型不能确定,或者是某个成员函数的参数或返回值的类型不能确定,就必须将此类声明为模板,它的存在不是代表一个具体的、实际的类,而是代表着一类类。

//templatedemo.h
#ifndef TEMPLATE_DEMO_HXX
#define TEMPLATE_DEMO_HXX

template <class T>
class test
{
  public:
    test(){};
    T add(T a,T b);
};
#endif


//templatedemo.cpp
#include <iostream>
#include "templatedemo.h"

template<class T>
T test<T>::add(T a,T b)
{
  return a+b;
}

int main()
{
  test<int> a;
  test<double> d;
  std::cout<<a.add(2,3)<<std::endl;
  std::cout<<d.add(5.0,6.1)<<std::endl;

  return 0;
}

 

posted @ 2015-08-11 16:04  cclhf  阅读(310)  评论(0编辑  收藏  举报