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

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 !
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值