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.