1. 程式人生 > >C++ Primer 第五版第八章程式設計練習節選(函式過載與模板函式)

C++ Primer 第五版第八章程式設計練習節選(函式過載與模板函式)

#include<iostream>
#include<cstring>

using namespace std;

const int Arsize = 40;

struct st 
{
	char ch[Arsize];
	int count;
};

void set(st &s, const char *ch);
void show(const st &s, int n = 1 );
void show(const char *ch, int n = 1);

int main()
{
	st s; 
	char testing[Arsize] = "Reality isn't what it used to be ! ";
	set(s, testing);
	show(s);
	show(s, 2);
	testing[0] = 'D';
	testing[1] = 'u';
	show(testing);
	show(testing, 2);
	show("Done");
	return 0;
}

void set(st &s, const char *ch)
{
	s.count = int(strlen(ch));
	int i = 0;
	while (i < s.count)
	{
		s.ch[i] = ch[i]; 
		i++;
	}
	s.ch[int(strlen(ch))] = '\0';
	cout << s.ch << " ## " << s.count << " $$ " << endl;
}

void show(const st &s, int n)
{
	while (n-- > 0)
	{
		cout << s.ch << endl;
	}
}

void show(const char *ch, int n)
{
	while (n-- > 0)
	{
		cout << ch << endl;
	}
}

#include<iostream>

using namespace std;

const int Arsize = 5;
template<typename T> T max5(T arr[]);
template<typename T> void show(T arr[]);

int main()
{
	int arr1[Arsize] = {1,2,3,4,5};
	double arr2[Arsize] = {1.5, 1.4, 1.3, 1.2, 1.1};
	cout << "The int type array is :  ";
	show(arr1);
	cout << "The maximun value is : " << max5(arr1) << endl;
	cout << "The double type array is : ";
	show(arr2);
	cout << "The maxium value is : " << max5(arr2) << endl;
	return 0;
}

template<typename T> T max5(T arr[])
{
	T temp = arr[0];
	for (int i = 1; i < Arsize; ++i)
	{
		if (temp < arr[i])
		{
			temp = arr[i];
		}
	}
	return temp;
}

template<typename T> void show(T arr[])
{
	for (int i = 0; i < Arsize; ++i)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}