C++中的代码重用(五)=>模板类功能的多样性

1.带有非类型参数

template<typename Type,int n>
class Array
{
private:
	Type data[n];
public:
	Array(){}
	explicit Array(const Type &d);
	Type & operator[](int i);
	const Type& operator[](int i) const{ return data[i]; }
};

这样便可以利用递归使用模板来创建数组

Array< Array<int, 4>, 5>num;//5*4
	Array<int, 5>sum(0);
	Array<double, 5>aver(0.0);

相比较利用构造函数来创建数组,表达式参数适用的是为自动变量维护的内存栈,执行速度较快,尤其在使用较小型数组时。

而构造函数一般较通用,可以将一种尺寸大小的数组赋给另一种尺寸大小数组。

2.使用多个类型参数,以及设置默认类型

template<typename T1,typename T2=int>
class Pair
{
private:
	T1 a;
	T2 b;
public:
	Pair(){}
	Pair(const T1 t1, const T2 t2) :a(t1), b(t2){}
	T1 geta(){ return a; }
	T2 getb(){ return b; }
	void show()const { cout << "a=" << a << ",b=" << b << endl; }
};

整体代码如下

//template_class.h
#ifndef TEMPLATE_CLASS_H_
#define TEMPLATE_CLASS_H_
/*数组模板*/
#include<iostream>
#include<cstdlib>
#include<string>
template<typename Type,int n>
class Array
{
private:
	Type data[n];
public:
	Array(){}
	explicit Array(const Type &d);
	Type & operator[](int i);
	const Type& operator[](int i) const{ return data[i]; }
};

template<typename T1,typename T2=int>
class Pair
{
private:
	T1 a;
	T2 b;
public:
	Pair(){}
	Pair(const T1 t1, const T2 t2) :a(t1), b(t2){}
	T1 geta(){ return a; }
	T2 getb(){ return b; }
	void show()const { cout << "a=" << a << ",b=" << b << endl; }
};
template<typename Type,int n>
Array<Type, n>::Array(const Type &d)
{
	for (int i = 0; i < n; i++)
		data[i] = d;
}
template<typename Type,int n>
Type & Array<Type,n>::operator[](int i)
{
	if (i < 0 || i >= n)
	{
		cout << "The index is out of range\n";
		exit(EXIT_FAILURE);
	}
	return data[i];
}
#endif //TEMPLATE_CLASS_H_

//main.cpp
/**
*Copyright U+00A9 2018 XXXXX. All Right Reserved.
*Filename:
*Author:XXXXX
*Date:2018.12.01
*Version:VS 2013
*Description:
**/

#include<iostream>
//#include<cstdlib>
#include"template_class.h"

using namespace std;
int main()
{
	Array< Array<int, 4>, 5>num;//5*4
	Array<int, 5>sum(0);
	Array<double, 5>aver(0.0);
	for (int i = 0; i < 5; i++)
	{
		cout << "please input " << i + 1 << " row element:";
		for (int j = 0; j < 4; j++)
		{
			cin >> num[i][j];
			sum[i] += num[i][j];
		}	
		aver[i] = (double)sum[i] / 4;
	}
	for (int i = 0; i < 5; i++)
		cout << "The average of " << i + 1 << " row is: "
		<< aver[i] << endl;
	Pair<string>p1("Hello,China!",99);
	Pair<int, string>p2(99,"Hello,China!");
	p1.show();
	p2.show();
	cout << "The element of p1 is: a=" << p1.geta() << ",b= " << p1.getb() << endl;
	cout << "The element of p1 is: a=" << p2.geta() << ",b= " << p2.getb() << endl;
  system("pause");
  return 0;
}

程序运行结果如下

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/85011582
今日推荐