Customization of C ++ Template: Custom C ++ class

zhaozj2021-02-11  182

Customization of C Template: Custom C class

The basic syntax of the class template is as follows:

Template

Class classname

{

......

}

T can be any type, I will give an example of a class template (please don't pursue this class, you need to write or have something to write, remember this is just example, our concern should be the characteristics of the language, this only Is it the most important, isn't it?).

Template

Class Operation

{

PUBLIC:

Operation (T T1, T T2): _ VAL1 (T1), _ VAL2 (T2) {}

~ Operation () {}

T Plus ()

{

Return_val1 _val2;

}

T minus ()

{

Return_val1-_val2;

}

T multiplies ()

{

Return_val1 * _val2;

}

T Divides ()

{

Return_val1 / _val2;

}

Private:

T _VAL1, _VAL2;

}

This class encapsulates four calculations. If t is a user-defined type, then the ' ', ',', '*', '/' operator must be overloaded. But when you declare a class object in the following way, you will encounter the problem, or you don't want this type to have similar operations.

Char szarr1 [] = "yuankai";

Char Szarr2 [] = "WinMain";

Operation OBJ2 (Szarr1, Szarr2);

Cout << Obj2.plus () << endl; // You may want to have different operations

Cout << Obj2. Divides () << endl; // You may not fully have this operation at all

What to do, of course, is customized. We can customize a statement to solve this problem.

Class Operation

{

PUBLIC:

Operation (Char * T1, Char * T2): _ VAL1 (T1), _ VAL2 (T2) {}

~ Operation () {}

Char * plus ()

{

Strcat (_val1, _val2); // should pay attention to overflow

Return_val1;

}

Void Display ()

{

Cout << _ VAL1 << endl;

COUT << _ VAL2 << Endl;

}

Private:

Char * _val1, * _ var2;

}

This way we can use the Operation class as follows.

Char szarr1 [] = "yuankai";

Char Szarr2 [] = "WinMain";

Operation Obj1 (1, 5);

Operation OBJ2 (Szarr1, Szarr2);

Cout << Obj1.divides () << endl;

Obj2.display ();

COUT << obj2.plus () << endl;

Cout << obj2.divides () << Endl; // will compile errors because there is no divides () function

Some visible template customization can give us full control, just like the cold acid's dental cream advertisement, how to use (eat) (eat). Not? Haha ... Understand the custom function template makes us more flexibility when using the C class, give us more free space.

The rush of the article, there is a typison or error, please pay more. Welcome to communicate with you. If everyone can, I will continue to write out (----- Yuan Kai -----).

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

New Post(0)