关于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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值