Conversion between C + + type data

Source: Internet
Author: User
Tags constructor integer

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.

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.