c++模板

函数模板

//函数模板
template<class T>//模板参数列表 --参数类型
void Swap(T& x1, T& x2)//函数参数列表 -- 参数对象
{
	T x = x1;
	x1 = x2;
	x2 = x;
}

int main()
{
	int a = 10, b = 3;
	Swap(a, b);
	return 0;
}

在这里插入图片描述

template<class T>
T Add(const T& left, const T& right)
{
	return left + right;
}
int main()
{
	int a1 = 10, a2 = 11;
	double d1 = 3.2, d2 = 3.1;

	cout << Add((double)a1, d2) << endl;
	//显示实例化
	cout << Add<int>(a1, d2) << endl;
	cout << Add<double>(a1, d2) << endl;
	return 0;
}

如果想直接用Add(a1,d2)可以像下面这样

template<class T1,class T2>
T1 Add(const T1& left, const T2& right)//返回值取决定因素
{
	return left + right;
}

上面两种方法都可以同时出现

//专门处理int的加法函数(现成)
int Add(int left, int right)
{
	return left + right;
}

//所有类型通用的加法函数(模板)
template<class T1, class T2>
T1 Add(const T1& left, const T2& right)//返回值取决定因素
{
	return left + right;
}

int main()
{
	int a1 = 10, a2 = 11;
	double d1 = 3.2, d2 = 3.1;
	cout << Add(a1, a2) << endl;//调用现成的
	cout << Add(d1, d2) << endl;//调用模板
	cout << Add(a1, d2) << endl;//调用模板
}

类模板

// 类模板
//Stack类名
//Stack<T>类型
template<class T>
class Stack
{
public:
	Stack(int capacity = 4)//全缺省
		:_top(0)
		, _capacity(capacity)
	{
		_a = new T[capacity];
	}

	~Stack()
	{
		delete[] _a;
		_a = nullptr;
		_top = _capacity = 0;
	}
	
	void Push(const T& x);

private:
	T* _a;
	int _top;
	int _capacity;
};

template<class T>
void Stack<T>::Push(const T& x)//要指定类域,才完整
{

}

int main()
{
	Stack<int> st1;   //存储int
	Stack<double> st2;//存储double
	Stack<char> st3;  //存储char
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值