C ++ conversion constructor and type conversion Constructor

Source: Internet
Author: User

C ++ conversion constructor and type conversion Constructor

Conversion constructor:

There is only one form parameter for the conversion constructor:

1 Student(float s)2 {3     score = s;4     age = 0;    5 }

If the constructor has been defined above:

1 Student (85); // creates the object c1. Since there is only one parameter, the conversion constructor is called.

If "+" is overloaded, the following is a compilation error:

1 stu2 = stu1 + 85; // This compilation Error 2 stu2 = stu1 + Student (85); // valid, convert 85 to Student Class Object

Note: When the corresponding conversion constructor has been defined, reload the operator "+"Youyuan FunctionWhen adding two plural values, you can use an exchange law;

If the function is a member function, the exchange law is not applicable;

 

Type conversion constructor:

A Conversion constructor can be used to convert a type of data into a class object, but cannot convert a class object into a type of data. Therefore, we need another method to implement this function:

C ++ provides a type conversion function to solve this problem:

1 operator float()2 {3     return score;4 }

The following is a simple example of using type conversion:

1 class Student 2 {3 private: 4 float score; 5 int age; 6 public: 7 Student (void) {age = 18; score = 0;} 8 Student (int, float s) {age = a; score = s;} 9 operator float () {return score;} 10}; 11 12 int main () 13 {14 Student stu1 (18, 86), stu2 (18, 97.5); 15 float f; 16 f = 6.75 + stu2; // when necessary, the compiler automatically calls these functions 17 cout <f <endl; 18 return 0; 19} 20/* 21 running result: 22 104.2523 Press any key to continue24 */

The compiler system calls this function because it finds that float is overloaded;

Note: There is no parameter before operator.

 

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.