Customization of C ++ template: custom member function and default class

zhaozj2021-02-11  193

Customization of C template: custom member function and default class

First, custom member functions

Customization template class members function is to define a class member function of a specified type to replace the member function of the template class definition to achieve a special function, thereby completing the customization of the template class member function.

Template

Class classname

{

PUBLIC:

ClassName (t t): _ VAL (t) {}

~ classname () {}

Void Display ();

Private:

T_val;

}

Template

Void classname :: Display ()

{

Cout << _ val << endl;

}

The above is a statement of a ClassName class, there is a Display () function in the ClassName class, which outputs member_val to the console. Below we will customize the Display () function in the ClassName class, making it different performance. , // Custom member Display () function:

Void classname :: Display ()

{

IF (NULL == _ VAL)

COUT << "no content" << endl;

Else

Cout << _ val << endl;

}

This is the CLASNAME Class Class DISPLAY () CHAR * Type Custom Member Function.

Second, the default type of template class

When declaring a template class, its class can provide a default.

Template

Class classname

{

PUBLIC:

T_val;

}

Declare a class classname object can be in two forms.

1. ClassName obj1; // Declare a variable as parameter as parameters

2. ClassName Obj2; // Declare a variable with the default type INT as a parameter

The rush of the article, there is a typison or error, please pay more. Thank you for your trip, I am grateful, welcome to communicate with you (---- Yuan Kai -----).

转载请注明原文地址:https://www.9cbs.com/read-5595.html

New Post(0)