Type Conversions Lecture 14 Wed Feb 22 2006
Type Conversions Lecture 14 Wed, Feb 22, 2006 Type Conversion
Topics n Constructors as type converters n Conversion operators 1/15/2022 Type Conversion 2
Conversion of Types n Frequently in a program an object must be converted from one type to another. n For the built-in types, this is done automatically whenever it is sensible. Convert float to int. n Convert int to float. n n How can it be done with created types? 1/15/2022 Type Conversion 3
Converting to a Created Type n A class uses its constructors to define rules for converting an object of another type to an object of that type. n The prototype is Class-name: : Class-name(other type); Rational: : Rational(int); Complex: : Complex(double); 1/15/2022 Type Conversion 4
Example: Convert int to Rational // // 1/15/2022 Rational constructor Rational: : Rational(int n) { numerator = n; denominator = 1; return; } Usages int i = 100; Rational r(i); Rational r = i; r = (Rational)i; r = Rational(i); Type Conversion 5
Example n How would you convert a Point to a Vector? 1/15/2022 Type Conversion 6
Converting to a Built-in Type n Sometimes we want to convert an object of a created type to an object of a built-in type. n For example, we might want to convert A Rational to a float. n A Complex to a double. n n For this we need a conversion operator. 1/15/2022 Type Conversion 7
Conversion Operators n A conversion operator has prototype Class-name: : operator built-in-type() const; n The operator converts the created-type object to the built-in type and returns the object of the built-in type. Rational: : operator float() const; Complex: : operator double() const; 1/15/2022 Type Conversion 8
Example: Convert Rational to float Rational: : operator float() const { return (float)numerator/denominator; } 1/15/2022 Type Conversion 9
- Slides: 9