1. Conversion between standard types of data
1.1 Implicit-type conversions
int i=6;
i=4.5+i; [Warning] converting to `int' from `double'
cout<<i<<endl;
Results:
10
The compiler gives a warning here because the compiler does a double type on 4.5, and when the expression is solved, 6 is converted to double, then the 4.5 is added to 10.5, and when the integer variable is assigned, the 10.5 is converted to an integer 10 and then assigned to I. The entire process is automatically completed by the C + + compiler, so such conversions are referred to as implicit type conversions.
1.2 Explicit type conversions
C + + also provides an explicit type conversion, in the form of a
Type name (data), such as int (11.1);//convert 11.1 to integral type 11.
2. Type conversions with transformation constructors
2.1 What is a transformation constructor
A constructor that has a parameter is usually used as a type conversion, which is called a transformation constructor (and a constructor with a parameter can be done without a type conversion). The function of a transformation constructor is to convert one of the other types of data into an object of a class.
2.2 Four kinds of constructors
So far, 4 types of constructors have been contacted, respectively (use cases as a plural class complex),
"1" default constructor.
Complex ()//No parameters
Or
Complex (double=0,double=0);//provide default parameter values
"2" used to initialize the constructor
Complex (double r,double i);//formal parameter list generally has more than two parameters
"3" copy constructor
Complex (complex&);//formal parameter is a reference to this class object
"4" Transformation constructor
Complex(double r){
real=r;
imag=0;
}
The function is to convert the parameter of double type to the object of the complex class, and the R as the real part of the complex, and the imaginary part is 0.