【C++】总结一:类函数和类模板 的模板和样例代码

一、函数模板

1. 模板

template<函数参数模板>
类型名 函数名(参数表)
{
函数体的定义
}

2. 例子

#include<iostream>
using namespace std;
template <typename T>// 或者 template <class T>
T abs(T x)
{
	return x < 0 ? -x : x;

}
int main()
{
	int n = 5;
	double m = -5.5;
	cout << abs(n) << endl;
	cout << abs(m) << endl;
	return 0;
}

二、类模板

1. 模板

类模板声明:

template<模板参数表>
class 类名
{
类成员声明
}

类模板以外定义成员函数:

template<模板参数表>
类型名 类名<模板参数识别符列表>::函数名(参数表)

使用模板类建立对象时:

模板名<函数参数表>对象名1, …对象名n;

2. 例子

#include<iostream>
using namespace std;
struct Student {
	int id;
	float gpa;
};

template <class T>
class Store {
private:
	T item;
	bool haveValue;
public:
	Store();
	T& getElem();
	void putElem(const T& x);
};
template<class T>
Store<T>::Store() :haveValue(false) {}

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

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

int main()
{
	Store<int>s1, s2;
	s1.putElem(3);
	s2.putElem(-7);
	cout << s1.getElem() << "  " << s2.getElem() << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值