You can use the same class template to create a set of objects of any type. In traditional C ++, there may be a floating point class or an integer class. If you use a class template, you can define a class number that applies to both of them.
Class template description
The general format of the class template description is:
Template <type parameter table>
Class <Class Name>
{// Class description body
};
Template <type parameter table>
<Return type> <Class Name> <type table name >:< member function 1> (parameter table)
{// Member function definition body}
Template <type parameter table>
<Return type> <Class Name> <type table name >:< member function 2> (parameter table)
{// Member function definition body}
...
12.3.2 use a class template
Like function templates, class templates cannot be used directly. They must be instantiated as corresponding template classes before they can be used.
After creating a class template, you can create an instance of the class template in the following ways:
<Class Name> <type real parameter table> <object table>;
The <type real parameter table> must match the <type parameter table> in the template. <Type real parameter table> is a template class, and <Object> is an object that defines the template class.
Use a class template to describe and define classes of any type. This type is called a parameterized class. If class is the promotion of objects, class templates can be said to be the promotion of classes.
Note: The difference between a class template and a template class.
A simple class template program (calculate the sum of two arbitrary types ).
Template <class T>
Class
{
Public:
A ();
A (T _ A, T _ B );
T Sum ();
PRIVATE:
T;
T B;
};
Template <class T>
A <t>: ()
{
A = 0; B = 0;
}
Template <class T>
A <t>: A (T _ A, T _ B)
{
A = _ A; B = _ B;
}
Template <class T>
T a <t>: sum ()
{
Return (A + B );
}
Void main ()
{
A <int> AI (3, 4 );
A <double> AD (3.1, 4.0 );
Cout <AI. sum () <"" <ad. sum () <Endl;
}
The program has been debugged in vc6.0. The above code is in a file. Do not put the class declaration in one. put the implementation in. in CPP, the class template does not support separation. Only the class declaration and definition can be placed in the same file.