100 學年度碩士班新生暑期課程 程式設計 Object-Oriented Programming: Part I The Basics of Classes.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Classes and Objects Systems Programming.
Classes and OOP. Basic, built-in, pre-defined types : char, int, double, … Variables + operations on them int a, b,c; c=a+b; c=a mod b; … More complicated,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Defining Classes.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
1 By Joaquin Vila Preparedbv Sally Scott ACS 168 Problem Solving Using the Computer Chapter 6 Classes Chapter 6 Classes.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
1 Fall 2002 ACS 168 Problem Solving Using the Computer Weeks 9 and 10 Structures and Classes Class Diagrams Weeks 9 and 10 Structures and Classes Class.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Defining Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Chapter 10 Defining Classes. Slide Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types.
1 Chapter 10 Defining Classes. 2 Overview Introduction Classes (10.2) Abstract Data Types and Structures (10.1)(10.3) Abstract Data Types and Structures.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Classes Definition A class is a data type whose variables are objects Object – a variable that has member functions as well the ability to hold.
Chapter 6 Defining Classes. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Introduction Structures (6.1) Classes (6.2)
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 10 Defining Classes.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
1 Class Features and Design Issues COSC 1567 C++ Programming Lecture 5.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Friend Functions.  An ordinary function that is given special access to the private members of a class  NOT a member function of the class  Prototype.
C/C++ Basics (V) Structures and Classes Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter Savitch, “Problem.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Individual Testing, Big-O, C++ Bryce Boe 2013/07/16 CS24, Summer 2013 C.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
CMSC 202 Lesson 8 Classes II. Warmup Declare a class (.h part) named “Cup” It has a data member that says how full it is One method called “Drink” that.
COMP 3000 Object-Oriented Programming for Engineers and Scientists Operator Overloading Dr. Xiao Qin Auburn University
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
CSIS 123A Lecture 1 Intro To Classes Glenn Stevenson CSIS 113A MSJC.
General Updates ● The Wiki is now back up to date. I have also added a working link to the lecture slides online. ● Whenever you notice something missing.
COMP 53 – Week Two Operator Overloading.
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Structures and Classes
What header file contains C++ file I/O instructions?
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
COMP 51 Week Twelve Classes.
Chapter 3: Using Methods, Classes, and Objects
Classes and Data Abstraction
Learning Objectives Classes Constructors Principles of OOP
Constructors and Other Tools
Classes and Objects Systems Programming.
Introduction to Classes and Objects
Presentation transcript:

100 學年度碩士班新生暑期課程 程式設計 Object-Oriented Programming: Part I The Basics of Classes

This slides are based on Chapters 6 and 7 of the following book. Walter Savitch, "Absolute C++," Third Edition, Addison-Wesley, 2008, ISBN:

Learning Objectives Classes – Defining, member functions – Public and private members – Accessor and mutator functions – Structures vs. classes Constructors – Definitions – Calling 3

Classes Similar to structures – Adds member FUNCTIONS – Not just member data Integral to object-oriented programming – Focus on objects Object: Contains data and operations In C++, variables of class type are objects 4

Class Definitions Defined similar to structures Example: class DayOfYear  name of new class type { public: void output();  member function! int month; int day; }; Notice only member function’s prototype – Function’s implementation is elsewhere 5

Declaring Objects Declared same as all variables – Predefined types, structure types Example: DayOfYear today, birthday; Declares two objects of class type DayOfYear Objects include: – Data Members month, day – Operations (member functions) output() 6

Question What is the difference between a class and an object? 7

Class Member Access Members accessed same as structures Example: today.month today.day – And to access member function: today.output();  Invokes member function 8

Class Member Functions Must define or "implement" class member functions Like other function definitions – Can be after main() definition – Must specify class: void DayOfYear::output() {…} :: is scope resolution operator Instructs compiler "what class" member is from Item before :: called type qualifier 9

Class Member Functions Definition Notice output() member function’s definition (in next example) Refers to member data of class – No qualifiers Function used for all objects of the class – Will refer to "that object’s" data when invoked – Example: today.output(); Displays "today" object’s data 10

Complete Class Example: Display 6.3 Class With a Member Function (1 of 4) 11

Complete Class Example: Display 6.3 Class With a Member Function (2 of 4) 12

Complete Class Example: Display 6.3 Class With a Member Function (3 of 4) 13

Complete Class Example: Display 6.3 Class With a Member Function (4 of 4) 14

Dot and Scope Resolution Operator Used to specify "of what thing" they are members Dot operator: – Specifies member of particular object Scope resolution operator: – Specifies what class the function definition comes from 15

A Class’s Place Class is full-fledged type! – Just like data types int, double, etc. Can have variables of a class type – We simply call them "objects" Can have parameters of a class type – Pass-by-value – Pass-by-reference Can use class type like any other type! 16

In-Class Exercise #1 Given the following class definition, write an appropriate definition for the member function set. class Temperature { public: void set(double newDegrees, char newScale); double degrees; char scale; // ‘F’ for Fahrenheit or ‘C’ for Celsius } 17

Encapsulation Any data type includes – Data (range of data) – Operations (that can be performed on data) Example: int data type has: Data: +-32,767 Operations: +,-,*,/,%,logical,etc. Same with classes – But WE specify data, and the operations to be allowed on our data! 18

Abstract Data Types "Abstract" – Programmers don’t know details Abbreviated "ADT" – Collection of data values together with set of basic operations defined for the values ADT’s often "language-independent" – We implement ADT’s in C++ with classes C++ class "defines" the ADT – Other languages implement ADT’s as well 19

More Encapsulation Encapsulation – Means "bringing together as one" Declare a class variable  get an object Object is "encapsulation" of – Data values – Operations on the data (member functions) 20

Principles of OOP Information Hiding – Details of how operations work not known to "user" of class Data Abstraction – Details of how data is manipulated within ADT/class not known to user Encapsulation – Bring together data and operations, but keep "details" hidden 21

Public and Private Members Data in class almost always designated private in definition! – Upholds principles of OOP – Hide data from user – Allow manipulation only via operations Which are member functions Public items (usually member functions) are "user-accessible" 22

Public and Private Example Modify previous example: class DayOfYear { public: void input(); void output(); private: int month; int day; }; Data now private Objects have no direct access 23

Public and Private Example 2 Given previous example Declare object: DayOfYear today; Object today can ONLY access public members – cin >> today.month; // NOT ALLOWED! – cout << today.day; // NOT ALLOWED! – Must instead call public operations: today.input(); today.output(); 24

Public and Private Style Can mix & match public & private More typically place public first – Allows easy viewing of portions that can be USED by programmers using the class – Private data is "hidden", so irrelevant to users Outside of class definition, cannot change (or even access) private data 25

Question Write the following program and compile it. What is the result? Why? #include using namespace std; class DayOfYear { public: void input(); void output(); private: int month; int day; }; int main() { DayOfYear today; cin >> today.month; cout << today.day; return 0; } void DayOfYear::input() { } void DayOfYear::output() { } 26

Accessor and Mutator Functions Object needs to "do something" with its data Call accessor member functions – Allow object to read data – Also called "get member functions" – Simple retrieval of member data Mutator member functions – Allow object to change data – Manipulated based on application 27

Separate Interface and Implementation User of class need not see details of how class is implemented – Principle of OOP  encapsulation User only needs "rules" – Called "interface" for the class In C++  public member functions and associated comments Implementation of class hidden – Member function definitions elsewhere – User need not see them 28

Question (1/2) Identify the interfaces and the implementations shown in Display 6.4. class DayOfYear { public: void input( ); void output( ); void set(int newMonth, int newDay); //Precondition: newMonth and newDay form a possible date. void set(int newMonth); //Precondition: 1 <= newMonth <= 12 //Postcondition: The date is set to the first day of the given month. int getMonthNumber( ); //Returns 1 for January, 2 for February, etc. int getDay( ); private: int month; int day; }; 29

Question (2/2) //Uses iostream and cstdlib: void DayOfYear::set(int newMonth, int newDay) { … } //Uses iostream and cstdlib: void DayOfYear::set(int newMonth) { … } int DayOfYear::getMonthNumber( ) { return month; } int DayOfYear::getDay( ) { return day; } 30

Structures versus Classes Structures – Typically all members public – No member functions Classes – Typically all data members private – Interface member functions public Technically, same – Perceptionally, very different mechanisms 31

In-Class Exercise #2 將課堂練習 #1(p.17) 的程式裡的 class 改為 struct ,重新編譯程式,結果有何不同? 32

Thinking Objects Focus for programming changes – Before  algorithms center stage – OOP  data is focus Algorithms still exist – They simply focus on their data – Are "made" to "fit" the data Designing software solution – Define variety of objects and how they interact 33

Constructors Initialization of objects – Initialize some or all member variables – Other actions possible as well A special kind of member function – Automatically called when object declared Very useful tool – Key principle of OOP 34

Constructor Definitions Constructors defined like any member function – Except: 1.Must have same name as class 2.Cannot return a value; not even void! 35

Constructor Definition Example Class definition with constructor: class DayOfYear { public: DayOfYear(int monthValue, int dayValue); //Constructor initializes month & day void input(); void output(); … private: int month; int day; } 36

Constructor Notes Notice name of constructor: DayOfYear – Same name as class itself! Constructor declaration has no return-type – Not even void! Constructor in public section – It’s called when objects are declared – If private, could never declare objects! 37

Question 將第 36 頁中的 constructor 由 public 改為 private 後 重新編譯,編譯結果為何? 38

Calling Constructors Declare objects: DayOfYear date1(7, 4), date2(5, 5); Objects are created here – Constructor is called – Values in parens passed as arguments to constructor – Member variables month, day initialized: date1.month  7 date2.month  5 date1.dat  4 date2.day  5 39

Constructor Equivalency Consider: – DayOfYear date1, date2 date1.DayOfYear(7, 4);// ILLEGAL! date2.DayOfYear(5, 5);// ILLEGAL! Seemingly OK… – CANNOT call constructors like other member functions! 40

Constructor Code Constructor definition is like all other member functions: DayOfYear::DayOfYear(int monthValue, int dayValue) { month = monthValue; day = dayValue; } Note same name around :: – Clearly identifies a constructor Note no return type – Just as in class definition 41

Alternative Definition Previous definition equivalent to: DayOfYear::DayOfYear(int monthValue, int dayValue) : month(monthValue), day(dayValue)  {…} Third line called "Initialization Section" Body left empty Preferable definition version 42

Constructor Additional Purpose Not just initialize data Body doesn’t have to be empty – In initializer version Validate the data! – Ensure only appropriate data is assigned to class private member variables – Powerful OOP principle 43

In-Class Exercise #3 修改第 41 頁中的程式,判斷月份與日期是否合理? 若否,則結束程式。 44

Overloaded Constructors Can overload constructors just like other functions Recall: a signature consists of: – Name of function – Parameter list Provide constructors for all possible argument-lists – Particularly "how many" 45

Class with Constructors Example: Display 7.1 Class with Constructors (1 of 3) 46

Class with Constructors Example: Display 7.1 Class with Constructors (2 of 3) 47

Class with Constructors Example: Display 7.1 Class with Constructors (3 of 3) 48

Constructor with No Arguments Can be confusing Standard functions with no arguments: – Called with syntax: callMyFunction(); Including empty parentheses Object declarations with no "initializers": – DayOfYear date1;// This way! – DayOfYear date(); // NO! What is this really? Compiler sees a function declaration/prototype! Yes! Look closely! 49

Explicit Constructor Calls Can also call constructor AGAIN – After object declared Recall: constructor was automatically called then – Can call via object’s name; standard member function call Convenient method of setting member variables Method quite different from standard member function call 50

Explicit Constructor Call Example Such a call returns "anonymous object" – Which can then be assigned – In Action: DayOfYear holiday(7, 4); Constructor called at object’s declaration Now to "re-initialize": holiday = DayOfYear(5, 5); – Explicit constructor call – Returns new "anonymous object" – Assigned back to current object 51

More About Explicit Constructor Call #include using namespace std; class Date { public: Date(int monthValue, int dayValue); void output(void); private: int month; int day; }; int main() { Date holiday(1, 1); cout << &holiday << endl; holiday.output(); holiday = Date(2,14); cout << &holiday << endl; holiday.output(); return 0; } Date::Date(int monthValue, int dayValue) { month = monthValue; day = dayValue; } void Date::output(void) { cout << month << "/" << day << endl; } 52

Default Constructor Defined as: constructor w/ no arguments One should always be defined Auto-Generated? – Yes & No – If no constructors AT ALL are defined  Yes – If any constructors are defined  No If no default constructor: – Cannot declare: MyClass myObject; With no initializers 53

Question (1/2) 以下兩個程式是否能正常編譯 ? 為什麼 ? – 程式一 : #include using namespace std; class DayOfYear { private: int month; int day; }; int main() { DayOfYear date1; } 54

Question (2/2) – 程式二 : #include using namespace std; class DayOfYear { public: DayOfYear(int monthValue, int dayValue); private: int month; int day; }; int main() { DayOfYear date1; } DayOfYear::DayOfYear(int monthValue, int dayValue) { month = monthValue; day = dayValue; } 55

Homework Define a class called Month that is an abstract data type for a month. Your class will have one member variable of type int to represent a month (1 for January, 2 for February, and so forth). Include all the following member functions: a constructor to set the month using the first three letters in the name of the month as three arguments, a construct to set the month using an integer as an argument (1 for January, 2 for February, and so forth), a default constructor, an input function that reads the month as an integer, an input function that reads the month as the first three letters in the name of the month, an output function the outputs the month as the first three letters in the name of the month, and a member function that returns the next month as a value of type Month. Embed your class definition in a test program. 繳交時間 : 2011/07/19 10:00-10:30 (Tue.) ,親自將程式檔案帶至教室, 逾時不候且不接受補交。 56