Presentation is loading. Please wait.

Presentation is loading. Please wait.

Type Conversions Lecture 13 Wed, Feb 21, 2007.

Similar presentations


Presentation on theme: "Type Conversions Lecture 13 Wed, Feb 21, 2007."— Presentation transcript:

1 Type Conversions Lecture 13 Wed, Feb 21, 2007

2 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

3 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

4 Example: Convert int to Rational
// Rational constructor Rational::Rational(int n) { numerator = n; denominator = 1; return; } // Usages Rational r(100); Rational r = 100; r = (Rational)100; r = Rational(100); 11/9/2018 Type Conversion

5 Example How would you convert a Point to a Vector? vectr.h
VectrTest.cpp point.h point.cpp 11/9/2018 Type Conversion

6 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

7 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

8 Example: Convert Rational to float
Rational::operator float() const { return (float)numerator/denominator; } 11/9/2018 Type Conversion

9 Convert a Rational to a Float
rational.h rational.cpp RationalTest.cpp 11/9/2018 Type Conversion


Download ppt "Type Conversions Lecture 13 Wed, Feb 21, 2007."

Similar presentations


Ads by Google