Download presentation
Presentation is loading. Please wait.
Published byΧθόνιος Βονόρτας Modified over 6 years ago
1
Type Conversions Lecture 14 Wed, Feb 22, 2006
2
Topics Constructors as type converters Conversion operators 11/9/2018
Type Conversion
3
Conversion of Types Frequently in a program an object must be converted from one type to another. For the built-in types, this is done automatically whenever it is sensible. Convert float to int. Convert int to float. How can it be done with created types? 11/9/2018 Type Conversion
4
Converting to a Created Type
A class uses its constructors to define rules for converting an object of another type to an object of that type. The prototype is Class-name::Class-name(other type); Rational::Rational(int); Complex::Complex(double); 11/9/2018 Type Conversion
5
Example: Convert int to Rational
// 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); 11/9/2018 Type Conversion
6
Example How would you convert a Point to a Vector? 11/9/2018
Type Conversion
7
Converting to a Built-in Type
Sometimes we want to convert an object of a created type to an object of a built-in type. For example, we might want to convert A Rational to a float. A Complex to a double. For this we need a conversion operator. 11/9/2018 Type Conversion
8
Conversion Operators A conversion operator has prototype
The operator converts the created-type object to the built-in type and returns the object of the built-in type. Class-name::operator built-in-type() const; Rational::operator float() const; Complex::operator double() const; 11/9/2018 Type Conversion
9
Example: Convert Rational to float
Rational::operator float() const { return (float)numerator/denominator; } 11/9/2018 Type Conversion
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.