Template ( Template Function & Template Class )

 

 
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <cmath>

using namespace System;

class CPoint {
public:
	int x;
	int y;
	CPoint() {
		this->x = rand()%10;
		this->y = rand()%10;
	}
	~CPoint() {}
};

class CPoint3D : public CPoint {
public:
	int z;
	CPoint3D() : CPoint() {
		this->z =  rand()%10;
	}
	~CPoint3D() {}
};

// template class
template <typename T>
class CVector {
public:
	double distance;
	T* pA;
	T* pB;
	CVector() {
		this->pA = new T();
		this->pB = new T();
		computeDistance( this->pA, this->pB );
	}
	~CVector() {}

	// OverLoading
	void computeDistance(CPoint* pA, CPoint* pB) { this->distance = pow( (double) pow( (double) ( pA->x - pB->x ) , 2 ) + pow( (double) ( pA->y - pB->y ) , 2 ) , 0.5 ); }
	void computeDistance(CPoint3D* pA, CPoint3D* pB) { this->distance = pow( (double) pow( (double) ( pA->x - pB->x ) , 2 ) + pow( (double) ( pA->y - pB->y ) , 2 ) + pow( (double) ( pA->z - pB->z ) , 2 ) , 0.5 ); }
};

// template function
template <class T>
void swap(T* A, T* B) {
	T Temp = *A;
	*A = *B;
	*B = Temp;
}

// bubble sort
template <class T>
void sort(T* arr[10]) {
	for(int i=10-1;i>=1;i--)
		for(int j=0;j<i;j++)
			if( arr[j]->distance > arr[j+1]->distance )
				swap( arr[j] , arr[j+1] );
}

int main(array<System::String ^> ^args)
{
	srand ( time(NULL) );
//------------------------------------------
	CVector<CPoint>* vec2D[10];
	CVector<CPoint3D>* vec3D[10];
//------------------------------------------
	for(int i=0;i<10;i++)
	{
		vec2D[i] = new CVector<CPoint>();
		vec3D[i] = new CVector<CPoint3D>();
	}
//------------------------------------------
	sort( vec2D );
	sort( vec3D );
//------------------------------------------
	return 0;
}
 

 

 

創作者介紹
創作者 Cuby 56 的頭像
Cuby 56

Cuby56

Cuby 56 發表在 痞客邦 留言(0) 人氣()