C + + Operators

Source: Internet
Author: User

1, conversion operators: A special class member function. When the operator is defined, the compiler will call it automatically where the built-in transformations can be used :

classsmallint{ Public: SmallInt (inti =0): M_val (i) {if(I <0|| i >255)            ThrowStd::out_of_range ("Bad SmallInt initializer"); }    //The conversion function must be a member function, usually defined as a const    operator int()Const{returnM_val;}Private: std::size_t m_val;};intMain () {SmallInt Si ( A); DoubleDval =4.5; //si converted to int, then converted to double    if(Si >=dval) {}    //si converted to int, then converted to bool    if(SI) {} cout<< si << Endl;//si converted to int//3.541 is converted to int first, and then the smallint object is constructed with intSmallInt Si2 =3.541; intIval = static_cast<int> (SI2) +3;//an explicit conversion    return 0;}

In addition, the language allows only one-time (Automatic) class-type conversions . That is, (only) through the conversion operator, if the C type can be converted to type B, the B type can be converted to type A, then the C type cannot be converted directly to type A.

Resources:

"C + + Primer"

Continue to learn in ...

C + + Operators

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.