Download presentation
Presentation is loading. Please wait.
Published byMelissa Blankenship Modified over 6 years ago
1
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Lecture Carrano CH1, C++ Interlude , C++ Interlude 5 C++ Book
2
Agenda Program 1 Discussion Deck of Cards: Class Design Encapsulation
Flush out card deck examples friends Constructors Call by Reference Overloading Operators: Rational Class
3
Program 1 Can I get away with a single constructor?
Where should I place const definitions? What do I need to turn in?
4
Class Design Simple Complete Cohesive Descriptive Intuitive Minimal
No Public Data Amenable to loosely couple
5
Problem 2 Design an interface for a class representing a deck of playing cards
6
#include "Card.h" #include "Hand.h" const int CARDS_IN_DECK = 52; class Deck { public: Deck(); ~Deck(); Card DealSingleCard(); Hand DealHand(int number); void Shuffle(); void Cut(); int CountCardsRemaining(); void ReturnHand(Hand theHand); void ReturnCard(Card theCard); int CountValuesRemaining(int val); int CountSuitsRemaing(Suit suit); bool isEmpty(); bool isComplete(); private: Card deck[CARDS_IN_DECK]; };
7
Interface Design Checklist
Constructors Setters/Getters Actions (verbs) Operator Overloads Private Data Types
8
Why C++ Object Oriented Programming (OOP)?
Abstraction <- Last Time Encapsulation <- This Time Hierarchy Polymorphism
9
Encapsulation
10
Encapsulation and Information Hiding
Wall: Not only encapsulate the entire implementation but also make it invisible/inaccessible. Slit: Interface of the implementation such as arguments and a return value. Implementation of method S Program that uses method S Function call with arguments Return a value
11
Class Classes: a new data type formed of a collection of data and a set of operations on the data Data Structures: a construct within a programming language that stores a collection of data Behave as a new data type add remove query Examples: student lists rational numbers complex numbers currency (cents/dollars) length measurement (inches/feet) weight measurement (oz/lbs) Program that uses a class
12
Encapsulation at ground level
Program consists of Driver file (main) – keep this quite small Classes (ex, MyClass) MyClass.h -- interface MyClass.cpp -- implementation Interface (.h file) public: functions called by others private: data, helper functions Implementation (.cpp file) MyClass::function()
13
Examples of private data Flush out deck example
const int CARDS_IN_DECK = 52; class Deck { public: Deck(); Card DealSingleCard(); Hand DealHand(int number); ….interface as defined last time…. ~Deck(); private: Card deck[52]; }; enum Suit { Heart, Diamond, Club, Spade }; class Card { public: Card(); Card(int val, Suit suit); ~Card(); private: int value; Suit suit; };
14
Friends Declared on either functions or classes
Identified with the friend keyword Non-member functions can access private data of an object if it has been declared a friend Friendship is not transitive (my friend’s friend is not my friend) Violates encapsulation class Foo { friend class TheClassToGrantAccess; public: private: }
15
Constructor Uses same name as class is constructs
Nothing returned; not even void Default constructor created Function executed on creation of object Arrays: constructors called in increasing order Arr[0], Arr[1], Arr[2],… Signature chooses constructor Casting of call parameters done using normal casting rules What’s in a constructor? Normally used initialize private data as built-in types in C++ are undefined (int a; a is unknown state) Generally side-effecting is not done
16
Add constructor(s) to Card
How about GETTERS/SETTERS?
17
CONST keyword usages Global definition of value which does not change
const int NUM_CARDS_IN_DECK = 52 (can also be done with preprocess #define but do not use) Modifier on member function which does not change data in object void MyFuntion(int p) const; const reference to save space on passing in variable void MyFunction(const MyParamType &mpt); There are other usages but the above are the most common/useful
18
Computer Scientist of the Week
Presper Eckert Chief Engineer first general purpose electronic digital computer (ENIAC) Vaccuum tubes Calculated ballistic tables for artillery Presented first course in computers (Moore School Lectures) Founded first commercial computer company Designed first commercial computer, UNIVAC Designed Von Neumann Architecture
19
C++ Fundamentals LET’S CODE
20
string http://www.cprogramming.com/tutorial/string.html
Mutable; Copied not shared. string firstName = "jimmy"; string lastName("hoffa"); string fullName; fullName = firstName + " " + lastName; cout << fullName << endl; cout << "First and last letters are:" << fullName[0] << " " << fullName[fullName.length() - 1] << endl; if (fullName == "jimmy hoffa") { cout << "Found !!!! "; } else cout << "oh where oh where have you gone";
21
Call by Value, Reference, and Constant Reference
struct Rectangle { int length; int width; }; int Area(Rectangle rect) int Area(Rectangle &rect) int Area(const Rectangle &rect) { int temp; temp = rect.length; rect.length = 35; return(temp * rect.width); } int main() { int result; Rectangle r = { 3, 3 }; result = Area(r); cout << "length = " << r.length << endl; cout << "width = " << r.width << endl; cout << "Area = " << result << endl; return 0; }
22
Class Bell
23
In class code Write a function which takes two integers and “swaps” them
24
Call by Value, Reference, and Constant Reference
Arrays, Pointers, and Structures Call by Value, Reference, and Constant Reference Which of swap functions is appropriate? void swap(string a, string b) { string tmp = a; a = b; b = tmp; } void swap(string &a, string &b) { string tmp = a; a = b; b = tmp; } void swap(const string &a, const string &b) { string tmp = a; a = b; b = tmp; } Which of findMax functions is appropriate? int findMax(vector<int> a) { int max = a[0]; int i; for (i=1; i < a.size(); i++) if (a[i] > max) max = a[i]; return max; } int findMax(vector<int> &a) { int max = a[0]; int i; for (i=1; i < a.size(); i++) if (a[i] > max) max = a[i]; return max; } int findMax(const vector<int> &a) { int max = a[0]; int i; for (i=1; i < a.size(); i++) if (a[i] > max) max = a[i]; return max; } CSS342: Introduction
25
Rational Class Create a class to represent a rational number
26
Rational Class Create a class to represent a rational number
This should allow for multiplication, division, addition, subtraction. Comparison (eg, ==, !=) Printing out to stream
27
Interface Design Checklist
Constructors Setters/Getters Actions (verbs) Operator Overloads Private Data Types
28
Rational.h: w/o Operating Overloads
#include <iostream> #include <algorithm> using namespace std; class Rational { public: Rational(); Rational(int num, int den); ~Rational(); int getNumerator() const; int getDemnominator() const; bool setValue(int num, int den); Rational Multiply(const Rational &rat) const; Rational Divide(const Rational &rat) const; Rational Subtract(const Rational &rat) const; Rational Add(const Rational &rat) const; void PrintRational(ostream &theStream) const; private: int numerator; int denominator; void reduce(); };
29
Rational.cpp: w/o Operator Overloading
Rational::Rational() { numerator = 0; denominator = 1; } Rational::Rational(int num, int den) numerator = num; denominator = den; reduce(); int Rational::getNumerator() const return numerator; int Rational::getDemnominator() const return denominator; bool Rational::setValue(int num, int den) { if (den == 0) return false; } numerator = num; denominator = den; reduce(); return true;
30
Rational.cpp: w/o Operator Overloading
void Rational::reduce() { int gcd = 1; int minimum = min(numerator, denominator); for (int i = 2; i <= minimum; i++) if (((numerator % i) == 0) && ((denominator % i) == 0)) gcd = i; } if (gcd > 1) numerator /= gcd; denominator /= gcd; Rational Rational::Multiply(const Rational &rat) const { Rational temp; temp.numerator = numerator * rat.numerator; temp.denominator = denominator * rat.denominator; temp.reduce(); return temp; } Rational Rational::Add(const Rational &rat) const { Rational temp; temp.numerator = (numerator * rat.denominator) + (rat.numerator * denominator); temp.denominator = denominator * rat.denominator; temp.reduce(); return temp; }
31
Operator Overload Allowing for operators to work on classes in intuitive ways. Key Examples: Arithmetic: +, -, *, / Comparison: ==, !=, <, >, <=, >= Input: <<, >> General rules for overloading Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded Always stick to the operator’s well-known semantics Always provide all out of a set of related operations Operators retain their precedence order
32
Overloading +,-,*,/ as member functions
class Rational { public: // Op Overloads Rational operator*(const Rational &rat) const; Rational operator/(const Rational &rat) const; Rational operator-(const Rational &rat) const; Rational operator+(const Rational &rat) const; };
33
Overloading input/output <<, >>
class Rational { public: friend ostream& operator<<(ostream &outStream, const Rational &rat); friend istream& operator>>(istream &inStream, Rational &rat); // Op Overloads Rational operator*(const Rational &rat) const; Rational operator/(const Rational &rat) const; Rational operator-(const Rational &rat) const; Rational operator+(const Rational &rat) const;
34
Overloading ==, !=, +=, etc…
class Rational { friend ostream& operator<<(ostream &outStream, const Rational &rat); friend istream& operator>>(istream &inStream, Rational &rat); public: // Op Overloads Rational operator*(const Rational &rat) const; Rational& operator*=(const Rational &rat); Rational operator/(const Rational &rat) const; Rational& operator/=(const Rational &rat); Rational operator-(const Rational &rat) const; Rational& operator-=(const Rational &rat); Rational operator+(const Rational &rat) const; Rational& operator+=(const Rational &rat); bool operator==(const Rational &rat) const; bool operator!=(const Rational &rat) const;
35
But wait… Given we overloaded +, is there a better way to implement +=? Actually, one should implement += first, and then used it to implement + Same for -=/-, *=/*, and / /=
36
Using += overload to implement +
MyClass & MyClass::operator+=(const MyClass &rhs) { ... // Do the compound assignment work. return *this; } MyClass MyClass::operator+(const MyClass &other) const MyClass result = *this; result += other; return result;
37
Resources on overloading.
-- rational class
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.