C++类模板学习

之前已经学习了函数模板,在这里,

C++函数模板Demo - win32 版_c++编写的opc da demo_bcbobo21cn的博客-CSDN博客

下面学习类模板;

VC6;

做一个星星类,Star;

Star.h;

#if !defined(AFX_STAR_H__97C0823A_2BCE_4D95_998D_D8C8D1A56308__INCLUDED_)
#define AFX_STAR_H__97C0823A_2BCE_4D95_998D_D8C8D1A56308__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

template

class Star{

public:
    Star(T1 a, T2 b): size(a), light(b){ }
public:
    T1 getsize() const;  //获取大小
    void setsize(T1 a);  //设置大小
    T2 getlight() const;  //获取亮度
    void setlight(T2 b);  //设置亮度

private:
    T1 size;  //大小
    T2 light;  //亮度
};

template  //模板头
T1 Star::getsize() const /*函数头*/ {
    return size;
}

template
void Star::setsize(T1 a){
    size = a;
}

template
T2 Star::getlight() const{
    return light;
}

template
void Star::setlight(T2 b){
    light = b;
}

#endif // !defined(AFX_STAR_H__97C0823A_2BCE_4D95_998D_D8C8D1A56308__INCLUDED_)

OnDraw()函数中调用,

void CMystarView::OnDraw(CDC* pDC)
{
	CMystarDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
	CString str1;

	Star star1(10, 20);
	str1.Format("星星大小:%d,星星亮度:%d", star1.getsize(), star1.getlight());
	pDC->TextOut(50, 50, str1);

    Star star2(100, "180度");
    str1.Format("星星大小:%d,星星亮度:%s", star2.getsize(), star2.getlight());
	pDC->TextOut(50, 80, str1);

    Star star3("六", "二十一度");
    str1.Format("星星大小:%s,星星亮度:%s", star3.getsize(), star3.getlight());
	pDC->TextOut(50, 110, str1);

	Star star4(5.5, 97.5);
    str1.Format("星星大小:%f,星星亮度:%f", star4.getsize(), star4.getlight());
	pDC->TextOut(50, 140, str1);
}

运行如下;

C++类模板学习_第1张图片 

 

 有时候把几个成员函数单独放到Star.cpp里,在VC环境会报链接错误,一时还没明白;下回继续;

你可能感兴趣的:(VC++,c++,类模板,泛型编程)