C + + Automatic type conversion--special constructor methods and overloaded operator methods

Source: Internet
Author: User

First, overloaded operator method

#include <stdio.h>#include<iostream>classthree{inti; Public: Three (intII =0,int=0): I (ii) {Std::cout<<"Call three ()"<<Std::endl; }};classfour{intx; Public: Four (intxx): X (XX) {}operatorThree ()Const{returnthree (x);}};voidg (three) {}intMain () { Four four (1);    g (four); G (1);//calls three (1,0)    intN; Std::cin>>N;}
Output two times:
Call Three ()

2. Constructor conversions

This constructor can take another type of object (reference) as its single argument, then the constructor allows the compiler to perform an automatic type conversion;
#include <stdio.h>#include<iostream>classone{ Public: One () {}};classtwo{ Public: Both (Constone&) {Std::cout<<"Call ()"<<Std::endl; }};voidF (both) {}intMain () {one one; f (one);//wants a, has a one
Output:"You Call ()"
    int i;     >> i;}
Note: The above method calls the hidden constructor of the other, do not use this if you are concerned about the efficiency of the call!

3. Preventing the constructor from being called implicitly requires that the call must be displayed:

When using keyword explicit, you must display the call to complete the type conversion
#include <stdio.h>#include<iostream>using namespacestd;classone{ Public: One () {}};classtwo{ Public: ExplicitBoth (Constone&) {}};voidF (both) {}intMain () {one one; //!f (one);//NO Auto Conversion allowedf (one); //inti; CIN>>i;}

C + + Automatic type conversion--special constructor methods and overloaded operator methods

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.