Class template general definition form
template <type parameter table> class class template name
{ //function body }
template <class Type>
class Container
{
Type u;
public:
void begin2(const Type& itnew);//声明函数
};
Class template member function definition form
template <type formal parameter list>
return type class template name <type name list>:: member function name (formal parameter list)
{ //function body }
template <class Type> void Container<Type>::begin2(const Type& p) {
//函数实现
u = p;
cout << u << endl;
}
Note: The name of the class template when defining the member function of the class template must be the same as when defining the class template, template <class Type>.
The class template is not a real class, the class needs to be regenerated, the form of the generated class, the class template name <type actual parameter table>, Container<int>.
Define the object.
Container<int> myContainer;//定义对象
#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);
}