今天在我编程史上写下了光辉的一页:成功的使用模板编程,不但方便灵活,而且使代码精简了一半。爽!
要求:在图像上画手画线或不规则多边形,然后计算它们的周长与面积,再把周长、面积写到图像上 以前的代码是编写两个函数,因为操作的对象不同,这里分别为:LAnnFreehand,LAnnPolyline,他们都是继承于LAnnotatiion 代码如下: /* *函数名称: CalcEllipseArea *函数功能: 计算椭圆面积 *函数参数1: &LAnn指定的注释类 *函数参数2:uAnnEvent响应事件类型 *返 回 值: 返回计算出的不规则模板的周长与面积字符串 *说 明: 为了适应不同的不规则注释,该函数使用泛型编程方法 * 使用模板定义所注释的类,可以大大节省代码空间 */ template<class T> CString CAnnDemoBitmap::CalcAbnormityTemp(T &LAnn,L_UINT uAnnEvent ) { int nPointCount; LBuffer LeadBuffer ; pANNPOINT pPoints = NULL; file://对象点的指针 int nRet; file://返回值 int nGirth; int nArea; CString strMsg; file://annotation name
if (uAnnEvent == LTANNEVENT_AUTOITEMCHANGED) { nPointCount = LAnn->GetPointCount(); } else { nPointCount = LAnn->GetPointCount() + 1; }
LeadBuffer.Reallocate( sizeof( ANNPOINT ) * nPointCount ); pPoints = ( pANNPOINT )LeadBuffer.Lock() ; file://Now, get the points nRet=LAnn->GetPoints( pPoints ); pPoints[ nPointCount - 1 ] = pPoints[ 0 ]; nRet=LAnn->SetPoints( pPoints, nPointCount ); nGirth = CalcHandLineGirth( nPointCount, pPoints ); nArea = CalcHandLineArea( nPointCount, pPoints ); strMsg.Format( "Girth:%dpixel Area:%d pixel", nGirth, nArea ); LeadBuffer.Unlock(); LeadBuffer.Free();
return strMsg; } 哇,原来使用泛型编程是如此之爽!

|