Type Conversions - PowerPoint PPT Presentation

About This Presentation
Title:

Type Conversions

Description:

Frequently in a program an object must be converted from one type to another. ... Usage. int i = 100; Rational r; r = (Rational)i; r = Rational(i); 12/19/09 ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 9
Provided by: robbko
Learn more at: http://people.hsc.edu
Category:

less

Transcript and Presenter's Notes

Title: Type Conversions


1
Type Conversions
  • Lecture 14
  • Wed, Feb 18, 2004

2
Topics
  • Constructors as type converters
  • Conversion operators

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?

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-nameClass-name(other type)
RationalRational(int) ComplexComplex(double)
5
Example Convert int to Rational
// Rational constructor RationalRational(in
t n) numerator n
denominator 1 return // Usage
int i 100 Rational r r
(Rational)i r Rational(i)
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.

7
Conversion Operators
  • A conversion operator has prototype

Class-nameoperator built-in-type() const
  • The operator converts the created-type object to
    the built-in type and returns the object of the
    built-in type.

Rationaloperator float() const Complexoperato
r double() const
8
Example Convert Rational to float
Rationaloperator float() const return
(float)numerator/denominator
Write a Comment
User Comments (0)
About PowerShow.com