【C++】类模板使用技巧

类模板一般定义形式
template <类型形式参数表> class 类模板名
{
    //函数体
}

template <class Type>
class Container
{
	Type u;
public:
	
	void begin2(const Type& itnew);//声明函数
};

 类模板成员函数定义形式
template <类型形式参数表>
返回类型 类模板名 <类型名表>::成员函数名(形式参数列表)
{
    //函数体
}

template <class Type> void Container<Type>::begin2(const Type& p) {
	//函数实现
	u = p;
	cout << u << endl;
}

注:类模板的成员函数定义时的类模板名与类模板定义时要一致,template <class Type> 。
类模板不是一个真实的类,需要重新生成类,生成类的形式,类模板名 <类型实在参数表>,Container<int> 。

 定义对象。

Container<int> myContainer;//定义对象

 【C++】模板描述

#include<iostream>
using namespace std;

template <class Type>
class Container
{
	Type u;
public:
	
	void begin2(const Type& itnew);//声明函数
};

template <class Type> void Container<Type>::begin2(const Type& p) {
	//函数实现
	u = p;
	cout << u << endl;
}
int main() {
	Container<int> myContainer;//定义对象
	
	int i = 100;
	myContainer.begin2(i);
	
}

猜你喜欢

转载自blog.csdn.net/weixin_41865104/article/details/108037023