关于template的作用

1.概述

template:模板 即提供一种模板标准。在C++中最重要的特征之一就是代码重用,为了实现代码的重用,代码需要具有通用性,就不受数据类型的影响,所以说template就是解决此问题的。。直白点就是用T来代替任意类型。类似重载。但模板在编译时不会产生任何目标代码。。

2.分类

(1)函数模板
(2)类模板

#include<iostream>
#include<string.h>
using namespace std;
struct student{
	int id;
	string name;
};
template <class T>
class Store{
	private:
	T item;
	bool haveValue;
	public:
		Store();
		T getitem();
		void putitem(T x);
};
template <class T>
Store<T>::Store():haveValue(false){
}

template <class T>
T Store<T>::getitem(){
	if(!haveValue){
			cout<<"no item"<<endl;
	exit(1);
	}

	return item;
}

template <class T>
void Store<T>::putitem(T x){
	haveValue=true;
	item=x;
}

int main(){
	
	
	Store<int>s1,s2;
	
	s1.putitem(3);
	s2.putitem(-3);
	cout<<s1.getitem()<<" "<<s2.getitem()<<endl;
student sp={100,"LI"};
	
	Store<student>s;
	s.putitem(sp);
	cout<<s.getitem().id<<""<<s.getitem().name;
	
	return 0;
	
	
}

注意:方法实现时注意跟上 template 相当于函数模板。。
声明 函数名 <类型> s1,s2

猜你喜欢

转载自blog.csdn.net/qq_44654974/article/details/105940121
今日推荐