Operator overloading of automatic type conversions

Source: Internet
Author: User

The second method of automatic type conversion is operator overloading, which is in the form of the operator destination type (); This function converts the current type to the desired type by following the operator of the type to which you want to convert the keyword. This form of operator overloading is unique because no return value type is specified, and its return value type is the name of the overloaded operator.

1#include <iostream>2 using namespacestd;3 4 classthree{5     inti;6  Public:7Three (intIi=0): I (ii) {8 9     }Ten  One }; A  - classfour{ -     intx; the  Public: -Four (intxx): X (xx) { -          -     } +     operatorThree ()Const{//An overloaded operator that converts an object of type four into an three object.  -         returnthree (x); +     } A }; at  -  - voidg (three) { -  - } -  in intMain () { -Four Four (1); to g (four);//Call type conversion operator, operator three () const {return three (x);} +G1);//Call type conversion constructorThree (int ii=0)
 +}

In the automatic type conversion technique, the constructor technique is the destination class that performs the conversion, but using the operator technique, is the source class that performs the conversion. One drawback of the constructor technique is that it is not possible to convert from a user-defined type to a built-in type, from a user-defined type to a built-in type that only operator overloading might do.

Operator overloading of automatic type conversions

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.