SlideShare ist ein Scribd-Unternehmen logo
1 von 56
DATA ABSTRACTION: USER DEFINED TYPES AND THE CLASS
DATA TYPES A  DATA TYPE  IS A FORMAL DESCRIPTION OF: 1. THE DOMAIN THAT AN OBJECT OF THAT TYPE CAN HAVE. 2. THE BASIC SET OF OPERATIONS THAT CAN BE APPLIED TO VALUES OF THAT TYPE. 3. DATA REPRESENTATION.
THE FORMAL DESCRIPTION OF  int  AND  float  VALUES AND THE ALLOWABLE OPERATIONS ON SUCH DATA TYPE COME FROM MATHEMATICS. THE OPERATIONS ARE:  + ,  - ,   * ,  AND   / .  THE RANGE OF VALUES CAN BE LISTED AS  INT_MIN  TO  INT_MAX .
[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object]
[object Object],[object Object],DATA ABSTRACTION: SIMPLE TYPES (USER-DEFINED)
EXAMPLE: TYPE DEFINITION  typedef   existing_type_name new_type_name ;
A  SIMULATION  OF THE TYPE  Logical : typedef int   Logical; const Logical TRUE = 1; const Logical FALSE = 0; : Logical positive;  :  positive = TRUE;  // initialize flag
MORE ON DATA ABSTRACTION ABSTRACT DATA TYPES PROVIDE FOR THE ABILITY TO MODEL THE DOMAIN AND OPERATIONS OF DATA WITHOUT ANY CONCERN ABOUT IMPLEMENTATION.
THE CASE OF THE "COUNTER" A COUNTER IS A SIMPLE INTEGER VARIABLE. ITS VALUE IS CHANGED AND ACCESSED DEPENDING ON SOME OTHER TASK.
COMMON OPERATIONS PERFORMED  (ON THE INTEGER VARIABLE)  ARE: 1. CLEAR (START AT SOME INITIAL VALUE) 2. ALTER THE VALUE TO KEEP TRACK OF TASK (INCREMENT) 3. ALTER THE VALUE TO KEEP TRACK OF TASK (DECREMENT) 4. EXAMINE OR PRINT THE CURRENT VALUE (ACCESS)
EXAMPLE: PROBLEM : GRADUATION CERTIFICATION REFERS TO EVALUATING EARNED CREDITS TO ASSURE THAT STUDENTS HAVE SATISFIED CURRICULUM REQUIREMENTS.  SOME STUDENTS DO, SOME DO NOT.  DEVELOP AND IMPLEMENT A SYSTEM THAT KEEPS TRACK OF THOSE STUDENTS WHO ARE GRADUATING AND THOSE THAT ARE DELAYED BASED ON NUMBER OF CREDITS EARNED.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
2. SPECIFICATION  (ONLY REGARDING COUNTER) a)  OPERATIONS void Initialize(int); void Increment(); void Decrement(); int Access_Value(); b)  DATA int value;
GRAD-VALID VALIDATE GET_CREDITS  PRINT RESULT LEVEL 0 LEVEL 1 ,[object Object]
NEW CONCEPTS THE CLASS
RELATIONSHIP BETWEEN DATA AND OPERATIONS: SEPARATE ENTITIES PROCESS A DATA STRUCTURES CONTROL STRUCTURES PROCESS D PROCESS C PROCESS B
ALTERNATIVE REPRESENTATION THE  CLASS  , A SET OF OBJECTS, ALLOWS FOR THE REPRESENTATION OF DATA AND OPERATIONS INTO A COHESIVE UNIT.
RELATIONSHIP BETWEEN DATA AND OPERATIONS: A COHERENT UNIT CONTROL STRUCTURES AND DATA STRUCTURES PROCESS A PROCESS D PROCESS C PROCESS B DATA
THE C++ CLASS A MECHANISM TO MODEL OBJECTS WITH MULTIPLE ATTRIBUTES. THE C++ CLASS ALLOWS FOR THE DEFINITION A NEW TYPE OF DATA ACCORDING TO THE NEEDS OF THE PROBLEM, AND TO DEFINE OPERATIONS (METHODS) TO ACT UPON THE TYPE (ABSTRACT DATA TYPING).
INFORMATION HIDING THE ENCAPSULATION OF IMPLEMENTATION DETAILS.  PRIVATE CODE AND DATA CANNOT BE ACCESSED DIRECTLY.
CLASS SYNTAX class  <class_name> { public: <public declaration list> private: <private declaration list> };
class  <class_name> { public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <private data structures> // optional <function prototypes> // optional };
EXAMPLE 1 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SYNTAX OF DEFINING  MEMBER FUNCTIONS <return_type>  <class_name> :: <function_name>     ( <parameter_list> ) { <function member body> }
EXAMPLE 1 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Class Scope and Accessing Class Members ,[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
IMPLEMENTATION: THE  Counter  CLASS // File: Counter.h #include <limits.h> // contains definitions of // INT_MAX and INT_MIN class Counter { public:  // member functions void Initialize(int init_value); // initialize counter void Increment(); // increment counter void Decrement(); // decrement counter int Access_Value(); // return current counter // value private:   // data members int value; };
void Counter::Initialize(int init_value) // initialize counter { value = init_value; } // Initialize() void Counter::Increment()  // increment counter { if (value < INT_MAX) value++; else cerr << &quot;Counter overflow. Increment ignored.&quot; << endl; } // Increment()
void Counter::Decrement()  // decrement counter { if (value > INT_MIN) value--; else cerr << &quot;Counter underflow. Decrement ignored.&quot; << endl; } // Decrement() int Counter::Access_Value() // return current counter value { return value; } // Access_Value()
#include <iostream.h> #include &quot;Counter.h&quot; void main() {  // Minimum credits for graduation const int GRAD_LEVEL = 130; // local objects of class Counter Counter c_graduated; Counter c_delayed; // local data int class_size, number_of_credits; int i; // get the graduating class size cout << &quot;Enter the class size: &quot;; cin >> class_size; IMPLEMENTATION (USING THE  Counter  CLASS)
// initialize counter values c_graduated.Initialize(0); c_delayed.Initialize(class_size); // use of Increment() and Decrement() for (i = 0; i < class_size; i++) {  cout << &quot;Please enter the number of validated credits: &quot;; cin >> number_of_credits; if (number_of_credits >= GRAD_LEVEL) { c_graduated.Increment(); c_delayed.Decrement(); } }  // print results using Access_value() cout << &quot;The number of students graduating this semester: &quot;  <<  c_graduated.Access_Value() << endl; cout << &quot;The number of students delayed this semester: &quot;  <<  c_delayed.Access_Value() << endl; return; }
[object Object]
Constructors ,[object Object],[object Object],[object Object],[object Object]
Default Constructor ,[object Object],[object Object],[object Object],[object Object]
Destructor ,[object Object],[object Object],[object Object],[object Object],[object Object]
ANOTHER EXAMPLE: PROBLEM : USING FLOATING POINT NOTATION TO REPRESENT FRACTIONS MAY PRODUCE APPROXIMATE RESULTS.  FOR EXAMPLE, THE RATIONAL NUMBER 1/3 IS 0.33333. REGARDLESS OF THE NUMBER OF ACCURATE DIGITS, IT WOULD BE IMPOSSIBLE TO PRECISELY REPRESENT SUCH A NUMBER.  DESIGN, DEVELOP AND IMPLEMENT A SYSTEM TO REPRESENT FRACTIONS ACCURATELY. AS AN EXAMPLE, WE WILL IMPLEMENT THE ADDITION OPERATION ONLY.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
2. CLASS SPECIFICATION A)  PUBLIC CONSTRUCT: Fraction(int n, int d = 1); Fraction(); void Get(); void Show(); double Evaluate(); B)  PRIVATE int numerator; int denominator; C)  FRIEND friend Fraction operator+ (Fraction f1,  Fraction f2);
NEW CONCEPTS FRIEND FUNCTIONS, OPERATOR OVERLOADING, AND CONSTRUCTORS
class  <class_name> { friend  <function prototype> ; // optional public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <data structures> // optional <function prototypes> // optional };
class Fraction { // operator overload, so we can do fractional arithmetic  // using a familiar operator, the  &quot;+&quot;  sign friend Fraction operator+ (Fraction f1, Fraction f2); public: : private: : }; FRIEND FUNCTIONS AND OPERATOR OVERLOADING
class Fraction { : public: Fraction(int n, int d = 1); // constructor Fraction();  // another constructor : private: : }; CONSTRUCTORS
// File: Fraction.h // The class declaration for fractions is included in this // header file. We represent a fraction using a pair of integers: // the numerator (top part) and denominator (bottom part). // This class definition includes more than the rational  // numbers, since the number infinity is permitted (a fraction // with a zero denominator--except 0/0)
class Fraction { // operator overload, so we can do fractional arithmetic  // using a familiar operator , the  &quot;+&quot;  sign   friend Fraction operator+ (Fraction f1, Fraction f2); public: Fraction(int n, int d = 1);  // constructor // Set numerator = n, denominator = d // if no second argument, default to 1 // another constructor: Fraction(); // Set numerator = 0, denominator = 1 void Get(); // Get a fraction from keyboard void Show(); // Display a fraction on screen double Evaluate(); // Return the decimal value of a fraction private: int numerator; // top part int denominator; // bottom part };
// File: Fraction.cpp // The class definition for fractions #include <iostream.h> #include &quot;Fraction.h&quot; Fraction operator+ (Fraction f1, Fraction f2) // Override of operator &quot;+&quot; for fraction addition { Fraction r;   // the return value of f1 + f2   // compute numerator r.numerator =  (f1.numerator * f2.denominator) +    (f2.numerator * f1.denominator);    // compute denominator r.denominator = f1.denominator * f2.denominator; return r;   // return the result }
Fraction::Fraction(int n, int d) // A Fraction constructor which allows the numerator and // denominator to be specified { numerator = n; denominator = d; }
Fraction::Fraction() // Another constructor. If no arguments specified, default to 0/1  { numerator = 0; denominator = 1; }
void Fraction::Get() // Get a fraction from standard input, in the form  // &quot;numerator/denominator&quot; { char div_sign; // used to consume the '/' character during input cin >> numerator >> div_sign >> denominator; }
void Fraction::Show()  // Display a fraction, in the form &quot;numerator/denominator&quot; { cout << numerator << '/' << denominator; }
double Fraction::Evaluate()  // Calculates and returns the decimal value of a fraction { double n = numerator; // convert numerator to float  double d = denominator; // convert denominator to float  return (n / d); // return float representation }
// File: TestFraction.cpp // Test the Fraction class #include <iostream.h> // for output #include &quot;Fraction.h&quot; // for Fraction declarations void main() { // Fraction constructors Fraction f1(3, 2), f2(4), f3, f4; // Display the fractions  cout << endl << &quot;The fraction f1 is &quot;; f1.Show(); cout << endl << &quot;The fraction f2 is &quot;; f2.Show(); cout << endl << &quot;The fraction f3 is &quot;; f3.Show(); // Get and display a fraction cout << endl << &quot;Enter a fraction of your own: &quot;; f3.Get(); cout << endl << &quot;You entered &quot;; f3.Show();
// Add two Fractions using the overloaded operator f4 = f1 + f3; // Display the fractions and result cout << endl << endl << &quot;The sum of &quot;; f1.Show(); cout << &quot; and &quot;; f3.Show(); cout << &quot; is &quot;; f4.Show(); // Find and display the floating-point value of the Fraction cout << endl << &quot;The value of this fraction is &quot;  << f4.Evaluate() << endl; }

Weitere Àhnliche Inhalte

Was ist angesagt?

constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++HalaiHansaika
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
C++ Overview
C++ OverviewC++ Overview
C++ Overviewkelleyc3
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWithTheBest
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001Ralph Weber
 
Moving Average Filter in C
Moving Average Filter in CMoving Average Filter in C
Moving Average Filter in CColin
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIAjit Nayak
 

Was ist angesagt? (20)

Pointers
PointersPointers
Pointers
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
Basic c#
Basic c#Basic c#
Basic c#
 
Pointers
PointersPointers
Pointers
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Templates
TemplatesTemplates
Templates
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Moving Average Filter in C
Moving Average Filter in CMoving Average Filter in C
Moving Average Filter in C
 
Assignment2
Assignment2Assignment2
Assignment2
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 

Andere mochten auch

KivimÀki: Kouluterveyskysely
KivimÀki: Kouluterveyskysely KivimÀki: Kouluterveyskysely
KivimÀki: Kouluterveyskysely Kouluterveyskysely
 
АО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотоя
АО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотояАО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотоя
АО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотояАО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ĐšĐ°Đ·Ń‹ĐœĐ°"
 
Building a Website from Planning to Photoshop Mockup to HTML/CSS
Building a Website from Planning to Photoshop Mockup to HTML/CSSBuilding a Website from Planning to Photoshop Mockup to HTML/CSS
Building a Website from Planning to Photoshop Mockup to HTML/CSShstryk
 
Romania, my country, Dana B
Romania, my country, Dana BRomania, my country, Dana B
Romania, my country, Dana Bbalada65
 
Power Notes Atomic Structure Day 3
Power Notes   Atomic Structure Day 3Power Notes   Atomic Structure Day 3
Power Notes Atomic Structure Day 3jmori1
 
Power Notes Atomic Structure
Power Notes   Atomic StructurePower Notes   Atomic Structure
Power Notes Atomic Structurejmori1
 
S6 w2 chi square
S6 w2 chi squareS6 w2 chi square
S6 w2 chi squareRachel Chung
 
Track2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apac
Track2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apacTrack2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apac
Track2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apacOpenCity Community
 
Payfirma Mobile Payment App
Payfirma Mobile Payment AppPayfirma Mobile Payment App
Payfirma Mobile Payment AppPayfirma
 
TheBehaviourReport.com Profile
TheBehaviourReport.com ProfileTheBehaviourReport.com Profile
TheBehaviourReport.com ProfileOscar Habeenzu
 
Betiad
BetiadBetiad
Betiadbetiad
 
Heaven - escena baralla al parc
Heaven - escena baralla al parcHeaven - escena baralla al parc
Heaven - escena baralla al parcmvinola2
 
PFCongres 2012 - Rock Solid Deployment of PHP Apps
PFCongres 2012 - Rock Solid Deployment of PHP AppsPFCongres 2012 - Rock Solid Deployment of PHP Apps
PFCongres 2012 - Rock Solid Deployment of PHP AppsPablo Godel
 
Wind Lift Brochure Web
Wind Lift Brochure   WebWind Lift Brochure   Web
Wind Lift Brochure Webgm330
 
Anivesario wanderlan pereira lima
Anivesario wanderlan pereira limaAnivesario wanderlan pereira lima
Anivesario wanderlan pereira limaangical-piaui
 
C1320prespost
C1320prespostC1320prespost
C1320prespostFALLEE31188
 

Andere mochten auch (20)

KivimÀki: Kouluterveyskysely
KivimÀki: Kouluterveyskysely KivimÀki: Kouluterveyskysely
KivimÀki: Kouluterveyskysely
 
АО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотоя
АО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотояАО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотоя
АО "ĐĄĐ°ĐŒŃ€ŃƒĐș-ÒšĐ°Đ·Ń‹ĐœĐ°": ĐŸŃ€ĐŸĐ”Đșт стратДгОО разĐČотоя
 
Building a Website from Planning to Photoshop Mockup to HTML/CSS
Building a Website from Planning to Photoshop Mockup to HTML/CSSBuilding a Website from Planning to Photoshop Mockup to HTML/CSS
Building a Website from Planning to Photoshop Mockup to HTML/CSS
 
Romania, my country, Dana B
Romania, my country, Dana BRomania, my country, Dana B
Romania, my country, Dana B
 
Power Notes Atomic Structure Day 3
Power Notes   Atomic Structure Day 3Power Notes   Atomic Structure Day 3
Power Notes Atomic Structure Day 3
 
Power Notes Atomic Structure
Power Notes   Atomic StructurePower Notes   Atomic Structure
Power Notes Atomic Structure
 
S6 w2 chi square
S6 w2 chi squareS6 w2 chi square
S6 w2 chi square
 
Track2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apac
Track2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apacTrack2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apac
Track2 -ćˆ˜ćžŒæ–Œ----c ie-net-openstack-2012-apac
 
Payfirma Mobile Payment App
Payfirma Mobile Payment AppPayfirma Mobile Payment App
Payfirma Mobile Payment App
 
God's Hobby
God's HobbyGod's Hobby
God's Hobby
 
Software development company
Software development companySoftware development company
Software development company
 
TheBehaviourReport.com Profile
TheBehaviourReport.com ProfileTheBehaviourReport.com Profile
TheBehaviourReport.com Profile
 
Betiad
BetiadBetiad
Betiad
 
Cosug status-final
Cosug status-finalCosug status-final
Cosug status-final
 
Heaven - escena baralla al parc
Heaven - escena baralla al parcHeaven - escena baralla al parc
Heaven - escena baralla al parc
 
India
IndiaIndia
India
 
PFCongres 2012 - Rock Solid Deployment of PHP Apps
PFCongres 2012 - Rock Solid Deployment of PHP AppsPFCongres 2012 - Rock Solid Deployment of PHP Apps
PFCongres 2012 - Rock Solid Deployment of PHP Apps
 
Wind Lift Brochure Web
Wind Lift Brochure   WebWind Lift Brochure   Web
Wind Lift Brochure Web
 
Anivesario wanderlan pereira lima
Anivesario wanderlan pereira limaAnivesario wanderlan pereira lima
Anivesario wanderlan pereira lima
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 

Ähnlich wie C++lecture9

Java căn báșŁn - Chapter4
Java căn báșŁn - Chapter4Java căn báșŁn - Chapter4
Java căn báșŁn - Chapter4Vince Vo
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1rehan16091997
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referentialbabuk110
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpg_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpSatish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpsinghadarsh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharpMody Farouk
 

Ähnlich wie C++lecture9 (20)

C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Java căn báșŁn - Chapter4
Java căn báșŁn - Chapter4Java căn báșŁn - Chapter4
Java căn báșŁn - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 
Lecture5
Lecture5Lecture5
Lecture5
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Overloading
OverloadingOverloading
Overloading
 
02.adt
02.adt02.adt
02.adt
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 

Mehr von FALLEE31188

Mehr von FALLEE31188 (20)

Lecture4
Lecture4Lecture4
Lecture4
 
Lecture2
Lecture2Lecture2
Lecture2
 
L16
L16L16
L16
 
L2
L2L2
L2
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Functions
FunctionsFunctions
Functions
 
Field name
Field nameField name
Field name
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Chapter14
Chapter14Chapter14
Chapter14
 
Chapt03
Chapt03Chapt03
Chapt03
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Brookshear 06
Brookshear 06Brookshear 06
Brookshear 06
 
Book ppt
Book pptBook ppt
Book ppt
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
Assignment
AssignmentAssignment
Assignment
 
5 2
5 25 2
5 2
 

KĂŒrzlich hochgeladen

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 

KĂŒrzlich hochgeladen (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 

C++lecture9

  • 1. DATA ABSTRACTION: USER DEFINED TYPES AND THE CLASS
  • 2. DATA TYPES A DATA TYPE IS A FORMAL DESCRIPTION OF: 1. THE DOMAIN THAT AN OBJECT OF THAT TYPE CAN HAVE. 2. THE BASIC SET OF OPERATIONS THAT CAN BE APPLIED TO VALUES OF THAT TYPE. 3. DATA REPRESENTATION.
  • 3. THE FORMAL DESCRIPTION OF int AND float VALUES AND THE ALLOWABLE OPERATIONS ON SUCH DATA TYPE COME FROM MATHEMATICS. THE OPERATIONS ARE: + , - , * , AND / . THE RANGE OF VALUES CAN BE LISTED AS INT_MIN TO INT_MAX .
  • 4.
  • 5.
  • 6.
  • 7. EXAMPLE: TYPE DEFINITION typedef existing_type_name new_type_name ;
  • 8. A SIMULATION OF THE TYPE Logical : typedef int Logical; const Logical TRUE = 1; const Logical FALSE = 0; : Logical positive; : positive = TRUE; // initialize flag
  • 9. MORE ON DATA ABSTRACTION ABSTRACT DATA TYPES PROVIDE FOR THE ABILITY TO MODEL THE DOMAIN AND OPERATIONS OF DATA WITHOUT ANY CONCERN ABOUT IMPLEMENTATION.
  • 10. THE CASE OF THE &quot;COUNTER&quot; A COUNTER IS A SIMPLE INTEGER VARIABLE. ITS VALUE IS CHANGED AND ACCESSED DEPENDING ON SOME OTHER TASK.
  • 11. COMMON OPERATIONS PERFORMED (ON THE INTEGER VARIABLE) ARE: 1. CLEAR (START AT SOME INITIAL VALUE) 2. ALTER THE VALUE TO KEEP TRACK OF TASK (INCREMENT) 3. ALTER THE VALUE TO KEEP TRACK OF TASK (DECREMENT) 4. EXAMINE OR PRINT THE CURRENT VALUE (ACCESS)
  • 12. EXAMPLE: PROBLEM : GRADUATION CERTIFICATION REFERS TO EVALUATING EARNED CREDITS TO ASSURE THAT STUDENTS HAVE SATISFIED CURRICULUM REQUIREMENTS. SOME STUDENTS DO, SOME DO NOT. DEVELOP AND IMPLEMENT A SYSTEM THAT KEEPS TRACK OF THOSE STUDENTS WHO ARE GRADUATING AND THOSE THAT ARE DELAYED BASED ON NUMBER OF CREDITS EARNED.
  • 13.
  • 14. 2. SPECIFICATION (ONLY REGARDING COUNTER) a) OPERATIONS void Initialize(int); void Increment(); void Decrement(); int Access_Value(); b) DATA int value;
  • 15.
  • 17. RELATIONSHIP BETWEEN DATA AND OPERATIONS: SEPARATE ENTITIES PROCESS A DATA STRUCTURES CONTROL STRUCTURES PROCESS D PROCESS C PROCESS B
  • 18. ALTERNATIVE REPRESENTATION THE CLASS , A SET OF OBJECTS, ALLOWS FOR THE REPRESENTATION OF DATA AND OPERATIONS INTO A COHESIVE UNIT.
  • 19. RELATIONSHIP BETWEEN DATA AND OPERATIONS: A COHERENT UNIT CONTROL STRUCTURES AND DATA STRUCTURES PROCESS A PROCESS D PROCESS C PROCESS B DATA
  • 20. THE C++ CLASS A MECHANISM TO MODEL OBJECTS WITH MULTIPLE ATTRIBUTES. THE C++ CLASS ALLOWS FOR THE DEFINITION A NEW TYPE OF DATA ACCORDING TO THE NEEDS OF THE PROBLEM, AND TO DEFINE OPERATIONS (METHODS) TO ACT UPON THE TYPE (ABSTRACT DATA TYPING).
  • 21. INFORMATION HIDING THE ENCAPSULATION OF IMPLEMENTATION DETAILS. PRIVATE CODE AND DATA CANNOT BE ACCESSED DIRECTLY.
  • 22. CLASS SYNTAX class <class_name> { public: <public declaration list> private: <private declaration list> };
  • 23. class <class_name> { public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <private data structures> // optional <function prototypes> // optional };
  • 24.
  • 25. SYNTAX OF DEFINING MEMBER FUNCTIONS <return_type> <class_name> :: <function_name> ( <parameter_list> ) { <function member body> }
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31. IMPLEMENTATION: THE Counter CLASS // File: Counter.h #include <limits.h> // contains definitions of // INT_MAX and INT_MIN class Counter { public: // member functions void Initialize(int init_value); // initialize counter void Increment(); // increment counter void Decrement(); // decrement counter int Access_Value(); // return current counter // value private: // data members int value; };
  • 32. void Counter::Initialize(int init_value) // initialize counter { value = init_value; } // Initialize() void Counter::Increment() // increment counter { if (value < INT_MAX) value++; else cerr << &quot;Counter overflow. Increment ignored.&quot; << endl; } // Increment()
  • 33. void Counter::Decrement() // decrement counter { if (value > INT_MIN) value--; else cerr << &quot;Counter underflow. Decrement ignored.&quot; << endl; } // Decrement() int Counter::Access_Value() // return current counter value { return value; } // Access_Value()
  • 34. #include <iostream.h> #include &quot;Counter.h&quot; void main() { // Minimum credits for graduation const int GRAD_LEVEL = 130; // local objects of class Counter Counter c_graduated; Counter c_delayed; // local data int class_size, number_of_credits; int i; // get the graduating class size cout << &quot;Enter the class size: &quot;; cin >> class_size; IMPLEMENTATION (USING THE Counter CLASS)
  • 35. // initialize counter values c_graduated.Initialize(0); c_delayed.Initialize(class_size); // use of Increment() and Decrement() for (i = 0; i < class_size; i++) { cout << &quot;Please enter the number of validated credits: &quot;; cin >> number_of_credits; if (number_of_credits >= GRAD_LEVEL) { c_graduated.Increment(); c_delayed.Decrement(); } } // print results using Access_value() cout << &quot;The number of students graduating this semester: &quot; << c_graduated.Access_Value() << endl; cout << &quot;The number of students delayed this semester: &quot; << c_delayed.Access_Value() << endl; return; }
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. ANOTHER EXAMPLE: PROBLEM : USING FLOATING POINT NOTATION TO REPRESENT FRACTIONS MAY PRODUCE APPROXIMATE RESULTS. FOR EXAMPLE, THE RATIONAL NUMBER 1/3 IS 0.33333. REGARDLESS OF THE NUMBER OF ACCURATE DIGITS, IT WOULD BE IMPOSSIBLE TO PRECISELY REPRESENT SUCH A NUMBER. DESIGN, DEVELOP AND IMPLEMENT A SYSTEM TO REPRESENT FRACTIONS ACCURATELY. AS AN EXAMPLE, WE WILL IMPLEMENT THE ADDITION OPERATION ONLY.
  • 41.
  • 42. 2. CLASS SPECIFICATION A) PUBLIC CONSTRUCT: Fraction(int n, int d = 1); Fraction(); void Get(); void Show(); double Evaluate(); B) PRIVATE int numerator; int denominator; C) FRIEND friend Fraction operator+ (Fraction f1, Fraction f2);
  • 43. NEW CONCEPTS FRIEND FUNCTIONS, OPERATOR OVERLOADING, AND CONSTRUCTORS
  • 44. class <class_name> { friend <function prototype> ; // optional public: <public data structures> // optional <constructors> // optional <function prototypes> // optional private: // optional <data structures> // optional <function prototypes> // optional };
  • 45. class Fraction { // operator overload, so we can do fractional arithmetic // using a familiar operator, the &quot;+&quot; sign friend Fraction operator+ (Fraction f1, Fraction f2); public: : private: : }; FRIEND FUNCTIONS AND OPERATOR OVERLOADING
  • 46. class Fraction { : public: Fraction(int n, int d = 1); // constructor Fraction(); // another constructor : private: : }; CONSTRUCTORS
  • 47. // File: Fraction.h // The class declaration for fractions is included in this // header file. We represent a fraction using a pair of integers: // the numerator (top part) and denominator (bottom part). // This class definition includes more than the rational // numbers, since the number infinity is permitted (a fraction // with a zero denominator--except 0/0)
  • 48. class Fraction { // operator overload, so we can do fractional arithmetic // using a familiar operator , the &quot;+&quot; sign friend Fraction operator+ (Fraction f1, Fraction f2); public: Fraction(int n, int d = 1); // constructor // Set numerator = n, denominator = d // if no second argument, default to 1 // another constructor: Fraction(); // Set numerator = 0, denominator = 1 void Get(); // Get a fraction from keyboard void Show(); // Display a fraction on screen double Evaluate(); // Return the decimal value of a fraction private: int numerator; // top part int denominator; // bottom part };
  • 49. // File: Fraction.cpp // The class definition for fractions #include <iostream.h> #include &quot;Fraction.h&quot; Fraction operator+ (Fraction f1, Fraction f2) // Override of operator &quot;+&quot; for fraction addition { Fraction r; // the return value of f1 + f2 // compute numerator r.numerator = (f1.numerator * f2.denominator) + (f2.numerator * f1.denominator); // compute denominator r.denominator = f1.denominator * f2.denominator; return r; // return the result }
  • 50. Fraction::Fraction(int n, int d) // A Fraction constructor which allows the numerator and // denominator to be specified { numerator = n; denominator = d; }
  • 51. Fraction::Fraction() // Another constructor. If no arguments specified, default to 0/1 { numerator = 0; denominator = 1; }
  • 52. void Fraction::Get() // Get a fraction from standard input, in the form // &quot;numerator/denominator&quot; { char div_sign; // used to consume the '/' character during input cin >> numerator >> div_sign >> denominator; }
  • 53. void Fraction::Show() // Display a fraction, in the form &quot;numerator/denominator&quot; { cout << numerator << '/' << denominator; }
  • 54. double Fraction::Evaluate() // Calculates and returns the decimal value of a fraction { double n = numerator; // convert numerator to float double d = denominator; // convert denominator to float return (n / d); // return float representation }
  • 55. // File: TestFraction.cpp // Test the Fraction class #include <iostream.h> // for output #include &quot;Fraction.h&quot; // for Fraction declarations void main() { // Fraction constructors Fraction f1(3, 2), f2(4), f3, f4; // Display the fractions cout << endl << &quot;The fraction f1 is &quot;; f1.Show(); cout << endl << &quot;The fraction f2 is &quot;; f2.Show(); cout << endl << &quot;The fraction f3 is &quot;; f3.Show(); // Get and display a fraction cout << endl << &quot;Enter a fraction of your own: &quot;; f3.Get(); cout << endl << &quot;You entered &quot;; f3.Show();
  • 56. // Add two Fractions using the overloaded operator f4 = f1 + f3; // Display the fractions and result cout << endl << endl << &quot;The sum of &quot;; f1.Show(); cout << &quot; and &quot;; f3.Show(); cout << &quot; is &quot;; f4.Show(); // Find and display the floating-point value of the Fraction cout << endl << &quot;The value of this fraction is &quot; << f4.Evaluate() << endl; }

Hinweis der Redaktion

  1. Member access specifiers are always followed by a colon (:) and can appear multiple times in any order.
  2. CONSTRUCTOR: defining, call, overloading, no return type.