栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 函数模板 /类模板

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 函数模板 /类模板

意义:将一个数据类型做为参数进行传递,这样不需要为每个数据类型都写相同的代码。

C++中使用两个关键字来支持模板:‘template’'和‘typename’. 第二个关键字也可以使用'class'来替换

 函数模板 原型:

template
返回值类型  模板名(形参表)
{
    函数体
}

例程1:

#include 
using namespace std;
template  //类型参数
void Swap(T & x, T & y)
{
    T tmp = x;
    x = y;
    y = tmp;
}
int main()
{
    int n = 5, m = 4;
	Swap(n, m);  //编译器自动生成 void Swap (int &, int &)函数
	cout << "n=" << n << "  m="<
#include 
using namespace std;
template   //参数类型         
T MaxElement(T a[], int size) //size是数组元素个数
{
	T tmpMax = a[0];
	for (int i = 1; i < size; ++i)
		if (tmpMax < a[i])
			tmpMax = a[i];
	return tmpMax;
}
int main()
{
	int a[5] = { 1,5,2,3,4 };	
	cout << MaxElement(a, 5) << endl;
	
	return 0;
}

 根据实参 a 的类型,编译器通过 MaxElement 模板自动生成了一个 MaxElement 函数,原型为:int MaxElement(int a[], int size);

类模板原型:

template

class test{

        private:

        T  data_member;

......

}

例程1:

#include 
using namespace std;

template 
class Array {
	private:
		T* ptr;
		int size;
	public:
		Array(T arr[], int s);
		void print();
};

template 
Array::Array(T arr[], int s) {  //构造函数
	ptr = new T[s];
	size = s;
	for (int i = 0; i < size; i++)
		ptr[i] = arr[i];
}

template 
void Array::print() {  
	for (int i = 0; i < size; i++)
		cout << " " << *(ptr + i);
	cout << endl;
}

int main() {
	int arr[5] = { 1,3, 5, 7, 9 };
	Array a(arr, 5);
	a.print();
	return 0;
}

多个模板参数:

#include
using namespace std;

template
class A {	
public:
	A(T a,U b ) { 
		cout << "a="< a('a','0');
	A b(5,6);
	return 0;
}

 继承中的类模板语法

#include
using namespace std;
template //定义类模板
class A {
public:
	A(T x) { t = x; 	}
	void out() {
		cout << t << endl;
	}
protected:
	T t;
};

class B : public A < int>//子类B从模板类A继承
{
public:
    B(int i) : A(i)
	{
	
	}
	void printB()
	{
		    cout << "A:" << t << endl;
	}
 protected:
 private:
	 };

 void pintBB(B &b)
{
	    b.printB();
}
void printAA(A &a)  
{
	    a.out();
 }

void main()
{
	A  a(100); 
	printAA(a);
	
	B b(10);
	b.printB();
	
	return;
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/920922.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号