当前位置: 代码迷 >> 综合 >> 【C++】类模板
  详细解决方案

【C++】类模板

热度:5   发布时间:2024-02-11 17:23:29.0

类模板一般定义形式
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);}

 

  相关解决方案