C++类模板再学习
之前已经学习了C++类模板;类模板的写法和一般类的写法有很大的差别;不容易熟悉;下面再做一遍;
做一个椭圆类,成员有长轴长度和短轴长度;
// ellipse.h: interface for the ellipse class.
//
//
#if !defined(AFX_ELLIPSE_H__51CD537E_D0B0_40F9_AD63_92F0502C0430__INCLUDED_)
#define AFX_ELLIPSE_H__51CD537E_D0B0_40F9_AD63_92F0502C0430__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
template<class T1, class T2>
class ellipse
{
public:
ellipse(T1 a, T2 b) : older(a), lack(b){ }
public:
T1 getolder() const;
void setolder(T1 a);
T2 getlack() const;
void setlack(T2 b);
private:
T1 older; //长轴长度
T2 lack; //短轴长度
};
template<class T1, class T2>
T1 ellipse<T1, T2>::getolder() const {
return older;
}
template<class T1, class T2>
void ellipse<T1, T2>::setolder(T1 a){
older = a;
}
template<class T1, class T2>
T2 ellipse<T1, T2>::getlack() const{
return lack;
}
template<class T1, class T2>
void ellipse<T1, T2>::setlack(T2 b){
lack = b;
}
#endif // !defined(AFX_ELLIPSE_H__51CD537E_D0B0_40F9_AD63_92F0502C0430__INCLUDED_)
类名之前先写,
template<class T1, class T2>
T1和T2是两个成员的类型;
ellipse(T1 a, T2 b) : older(a), lack(b){ }
构造函数,接收2个参数,一个类型为T1,一个类型为T2;把a传给成员变量older,把b传给成员变量lack;
T1 older; //长轴长度
T2 lack; //短轴长度
成员变量的定义,类型写为T1、T2,T1、T2可以替换为C++的各种数据类型;
template<class T1, class T2>
每个成员函数体之前也写上这个;
调用如下;
void CTyView::OnDraw(CDC* pDC)
{
CTyDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str1;
ellipse<int, int> e1(100, 20);
str1.Format("长轴:%d,短轴:%d", e1.getolder(), e1.getlack());
pDC->TextOut(50, 50, str1);
ellipse<char*, char*> e2("20cm", "10cm");
str1.Format("长轴:%s,短轴:%s", e2.getolder(), e2.getlack());
pDC->TextOut(50, 80, str1);
ellipse<double, double> e3(155.5, 97.5);
str1.Format("长轴:%f,短轴:%f", e3.getolder(), e3.getlack());
pDC->TextOut(50, 140, str1);
}
运行;