C + + conversion constructors and type conversion functions

Source: Internet
Author: User

Look at the STL source, there is a piece of code feel very strange

return (Link_type) ((*node). Next); }

Iterator and Link_type are two different types, how can they return? Turning over the previous note, it was discovered that a temporary object was generated by the conversion constructor and then return.

The function of a conversion constructor is to convert some type of data into an object of a class, which is called a transform constructor when a constructor has only one parameter and is not a const reference to this class. Tried a little bit.

classa{ Public:    intA; A (inta): A (a) {} a Reta () {returnA; }};intMain () {A A (2); A b=A.reta (); A C=3; cout<<b.a<<"\ n"<<c.a<<Endl; return 0;}

The result is output 2 and 3

This is actually caused by the implicit conversion mechanism, and if you do not want this effect, you can add the explicit declaration before the constructor. Plus the code above will compile an error, prompting

Cannot convert from "int" to "A".

Since the data can be converted to a type, the type can also be converted to data. C + + type Conversion functions can convert an object of a class to a specified type of data.

The general form of a type conversion function is: operator type name () {implement translated statement} test code:
classa{ Public:    intA; A (inta): A (a) {}operator int()    {        returnA; }};intMain () {A A (2); intb = A +3; A C= A +4; cout<<b<<"\ n"<<c.a<<Endl; return 0;}

Result outputs 5 and 6

C + + conversion constructors and type conversion functions

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.