Operator in C ++ has two main functions:Operator OverloadingFirstOperator Conversion. Many people are familiar with Operator overloading. Let's use the following small example to learn more:
Class A {public: A operator + (A & OA) {A;. num = OA. num + num; return a;} int num;}; int main (INT argc, char * argv []) {A;. num = 1; a B; B. num = 2; a c; C = a + B; cout <"C. num: "<C. num <Endl ;}ProgramOutput: C. Num: 3;
Easy to understand. Next, we need to explain another major function of the Operator.Operator Conversion: Operator T
The syntax is very simple. Make a declaration in the member function declaration part of the class:
Class A {public:... operator int () {return num ;}; // if necessary, object A can be converted to an int type object. ... Int num ;};
This statement makes the following statement true:
Cout <C + 12 <Endl; // Where C is a type object
Another implicit type conversion occurs. This time, we can directly use the class object to generate another type. do you think of the implicit type conversion part of the constructor? Here is a small summary:
In the implicit type conversion section of the constructor, a temporary object of the current class is constructed using another type. Such conversion must be supported by the constructor; implicit type conversion of the Operator, use the current object to generate another type of object (opposite to the constructor type). This conversion must be supported by the operator.
Implicit type conversion has advantages and disadvantages, and the class designer plays a decisive role. If you do not want the constructor to undergo implicit type conversion, add the explicit keyword before the constructor. At the same time, the implicit type conversion declared by the operator can also be replaced by some corresponding return value functions, so that the user's control is better.
We recommend that you refer to the document "implicit type conversion" in this blog.