Operator usage in C ++: implicit type conversion

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.