C++自定义类模板

C++中有一个重要特性,那就是模板类型。类似于Objective-C中的泛型。C++通过类模板来实现泛型支持。

在引入typename之前,class关键字早已在模板申明中被使用。在typename关键字引入后,可以用它来替代class关键字。

如:template<class T1, class T2>  和  template<typename T1, typename T2>相同

1.普通的模板类:

1)定义一个temp的模板类:

template<class T>
class temp
{
public:
	temp();
	temp(T k);
	~temp(){}

	void print();
	T operator+(T j);
private:
	T m;
	const T i;
};

2)相关函数的实现

template<class T>
temp<T>::temp()
{
	i = 0;
	m = 0;
}
template<class T>
temp<T>::temp(T k) :i(k), m(k)
{
}

template<class T>
void temp<T>::print()
{
	cout << "n=" << m << endl;
	cout << "i=" << i << endl;
}
template<class T>
T temp<T>::operator+(T j)
{
	return m + j;
}

3)主函数

int main()
{
	temp<int> t(1);
	
	t.print();

	cout << t + 1 << endl;

	system("pause");
	return 0;
}

输出:

2.在模板类中加入静态成员

template<class T>
class temp
{
public:
	temp();
	temp(T k);
	~temp(){}

	void print();
	T operator+(T j);

    static int count;        //静态成员变量
private:
	T m;
	const T i;
};
template<class T> int temp<T>::count = 0;    //赋值

3.在模板类中加入模板函数

template<class T>
class STR
{
public:
	template<class T2>int compare(const T2&);
    ...
};
template<class T>template<class T2>int STR<T>::compare(const T2& s)
{
    ...
}

4.友元模板

template<class T>
class STR
{
public:
	template<class T2>int compare(const T2&);
	friend<class Type>friend class A;
	template<class Type>friend void D(B<Type>);
	template<class Type>friend void C::Cf();
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值