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