当前位置: 首页 > 工具软件 > Templates > 使用案例 >

C++面向对象(2):Templates

吴伟志
2023-12-01

Description:

Templates 使我们编写相同的代码不需要考虑不同的类型。Templates 在编译时候展开,类似宏。根据不同类型展开不同副本。

例一:冒泡排序

代码:

// CPP code for bubble sort
// using template function
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

template <class T> 
void bubbleSort(T number[], int n)
{
	for (int i = 0; i < n - 1; i++)
		for (int j = n - 1; i < j; j--)
			if (number[j] < number[j - 1])
				swap(number[j], number[j - 1]);
}

// Driver Code
int main()
{
	int number[5] = { 10, 50, 30, 40, 20 };
	int n = sizeof(number) / sizeof(number[0]);

	cout << "Unsorted array : " <<endl;
	for (int i = 0; i < n; i++)
		cout << number[i] << " ";
	cout << endl;
	// calls template function
	bubbleSort<int>(number, n);

	cout << "Sorted array : " <<endl;
	for (int i = 0; i < n; i++)
		cout << number[i] << " ";
	cout << endl;

	return 0;
}

Output:

Unsorted array : 
10 50 30 40 20 
Sorted array : 
10 20 30 40 50 

例二:定义多个参数

代码:

// using template function
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

template <typename T,typename U> 
class Student {
private:
	T name;
	U number;
public:
	Student() {
		cout<<"I am a Student !" <<endl;
	}
};

// Driver Code
int main()
{
	Student<string,int>a;
	Student<string,double>b;
	return 0;
}

Output:

I am a Student !
I am a Student !

例三:设置默认值

代码:

// using template function
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;

template <typename U , typename T = string> 
class Student {
private:
	T name;
	U number;
public:
	Student() {
		cout<<"I am a Student !" <<endl;
	}
};

// Driver Code
int main()
{
	Student<int>a;
	Student<double>b;
	return 0;
}

Output:

I am a Student !
I am a Student !
 类似资料: