模板类

#include 
using namespace std;

/**
 * 定义一个矩形类模板Rect
 * 成员函数:calcArea()、calePerimeter()
 * 数据成员:m_length、m_height
 */
template
class Rect
{
public:
   Rect(T len, T hei);
   ~Rect();
   T calcArea();
   T calePerimeter();
public:
    T m_length;
    T m_height;
};

/**
 * 类属性赋值
 */
template
Rect::Rect(T length, T height)
{
    m_length = length;
    m_height = height;
}

/**
 * 面积方法实现
 */
template
T Rect::calcArea()
{
    return m_length * m_height;
}

/**
 * 周长方法实现
 */
template
T Rect::calePerimeter()
{
    return ( m_length + m_height) * 2;
}
template
Rect::~Rect(){
    cout << "析构函数" << endl;
}
int main(void)
{
    Rect rect(3, 6);
    cout << rect.calcArea() << endl;
    cout << rect.calePerimeter() << endl;
    return 0;
}

你可能感兴趣的:(模板类)