C++类模板(新手必备)

版权声明:个人爱好,可随便转载 https://blog.csdn.net/qq_43528087/article/details/88957942

为什么要定义类模板呢

先看一个例子:两个数求和

#include <iostream>
using namespace std;

class Test
{
	public:
	    Test(int a, int b)
	    {
		    x = a;
			y = b;
		 }
		int add()
		{
			return (x + y);
		 }
	private:
	    int x, y;

};
int main()
{
	Test a(2, 4);
	cout << a.add() << endl;;

	system("pause");
	return 0;
}

以上代码只适用于整形变量求和,如果是float、double呢,还得专门定义一个类吗?如何避免大量的重复工作

类模板的定义

template <模板形参表>
class  类模板名 { //类体
    成员列表
};
类模板必须以关键字template开头,后接模板形参表(不允许为空)。

用类模板实现求和

#include <iostream>
using namespace std;

template <class Type>//类模板定义
class Test       //Test不是类名,而是模板名
{
	public:
	    Test(Type a, Type b)
	    {
		    x = a;
			y = b;
		 }
	    Type add()
		{
			return (x + y);
		 }
	private:
	    Type x, y;

};
int main()
{
	Test<double> a(2.4, 4);
	cout << a.add() << endl;;

	system("pause");
	return 0;
}

这样,我们就可以通过Type实现不同数据类型的求和了

扩展

如果在类模板外部定义成员函数,形式为:

template <模板形参表>
返回类型 类名<类型参数表>::函数名(形式参数列表)
{
   函数体

例如:

template  <class Type>
void Point  < Type >::Set(const Type a, const Type b)
{
   x = a; y = b;
}
用类模板定义对象时,必须为i模板形参显式指定类型参数

一般形式为:
类模板名<类型实参表> 对象名列表;
类模板名<类型实参表> 对象名1(实参列表1),对象名2(实参列表2),……
例如:

Point  < int >  a,b;
Point  < double>  m(1,2),n(3,4);
模板形参表还可以是非类型形参,形式与函数形参表相似

例如:

template <class Type,int N)
class Sequence  //Sequence是类模板
{
  public:
    void Set(int i,Type value);
    Type Get(int i){ return array[i];}
  private:
    Type array[N];
};
template <class Type,int N>
void Sequence <T,N>::Set(int i,Type value)
{
  array[i]=value;
}

定义类模板对象时:

Sequence <int,5> a;
Sequence <double,5> b;

猜你喜欢

转载自blog.csdn.net/qq_43528087/article/details/88957942