关于C++虚函数,纯虚函数以及模板等重要概念的深刻讨论(三)

4.模板函数与模板类ios

    其实我的认为C++模板的概念跟其余面向对象的语言中的泛型概念有些相似,在学习一门新的概念的时候咱们不妨将它跟它相似的概念类比的学习,这样印象会更加的深入,模板的引入会让程序更加的通用,同时避免了代码的冗余。app

    定义模板有两种方式,第一种:template<typename T1, typename T2> 第二种方式是:template<class T1, class T2> 本人推荐你们使用第一种方式,看起来比较直观;接下来咱们来看一下模板函数以及模板类的实例:函数

头文件:Test.h学习

#ifndef TEST2
#define TEST2
#include "iostream"
using namespace std;

template<typename T1, typename T2>
void swap(T1 &value1, T2 &value2)
{
	//Exchange of two Numbers
	T1 temp = value1;
	value1 = value2;
	value2 = temp;
	return;
}

template<typename T1, typename T2>
class A
{
private:
	T1 valueA;
public:
	A();
	A(T2 value);
	~A();
	T1 print(T2 value)
	{
		cout << "The Value is :" << value <<endl;
		return valueA;
	};
};
//The class A realize.
template<typename T1, typename T2> 
A<T1, T2>::A()
{
	valueA = 0;
}
template<typename T1, typename T2> 
A<T1, T2>::A(T2 value)
{
	valueA = value;
}
template<typename T1, typename T2>
 A<T1, T2>::~A()
{
	cout << "This is A class." << endl;
}
#endif

函数文件:Test.cppspa

// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Test2.h"

int main(void)
{
	char str1 = 'A';
	char str2 = 'B';

	A<int, char> *objectA = new A<int, char>(str1);
	int temp = objectA->print(str2);
	cout << "The A ASCII number is :" << temp << endl;

	int value1 = 12;
	int value2 = 13;
	double value3 = 14.12;

	cout << "Swap befor value1 = "<< value1 <<endl;
	cout << "Swap befor value2 = "<< value2 <<endl;
	swap<int, int>(value1, value2);
	cout << "Swap after value1 = "<< value1 <<endl;
	cout << "Swap after value2 = "<< value2 <<endl;

	cout << "Swap befor value1 = "<< value1 <<endl;
	cout << "Swap befor value3 = "<< value3 <<endl;
	swap<int, double>(value1, value3);
	cout << "Swap after value1 = "<< value1 <<endl;
	cout << "Swap after value3 = "<< value3 <<endl;

	return 0;
}

输出的结果为:code

        

从中能够看出咱们只定义了一个swap模板函数,却能够有不一样的入参;一样类A为模板类,能够给它定义不一样类型的对象,从而实现功能的多样化。对象

必定要注意的是要按照像上述代码那样来定义和实现模板类和模板函数,本人初学模板的时候也出现过不少概念上的错误。编译器

细心地人会发现,swap函数在交换value1和value3的时候发生了隐式的类型转换,即将doule类型转换为int类型,从而将14.12转换为14,固然在编译的时候编译器也会发出一个警告:io

        

因此利用模板的时候必定要仔细认真,要肯定这种隐式的类型转换,从而避免没必要要的错误发生。console

 

<未完待续>

相关文章
相关标签/搜索