Recitation Course 0603 Speaker: Liu Yu-Jiun.

Slides:



Advertisements
Similar presentations
Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
Advertisements

Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3.
 2008 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
Classes: A Deeper Look Systems Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Classes: A Deeper Look, Part But what, to serve our private ends, Forbids the cheating of our friends? ◦ Charles Churchill Instead of this absurd.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Chapter 18 - C++ Operator Overloading
CSE1002 – Problem Solving with Object Oriented Programming
Yan Shi CS/SE 2630 Lecture Notes
Procedural and Object-Oriented Programming
IS Program Design and Software Tools Introduction to C++ Programming
Chapter 13: Overloading and Templates
Lecture 5: Classes (continued) Feb 1, 2005
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
Class: Special Topics Copy Constructors Static members Friends this
8 Pointers.
group work #hifiTeam
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
Chapter 9 Classes: A Deeper Look, Part 1
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
10.2 const (Constant) Objects and const Member Functions
Operator Overloading.
Classes: A Deeper Look, Part 2
Operator Overloading; String and Array Objects
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
7 Arrays.
9-10 Classes: A Deeper Look.
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Classes: A Deeper Look, Part 2
Classes: A Deeper Look, Part 1
Chapter 18 - Operator Overloading
Operator Overloading; String and Array Objects
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
(4 – 2) Introduction to Classes in C++
Introduction to Classes and Objects
Presentation transcript:

Recitation Course 0603 Speaker: Liu Yu-Jiun

10.6 Dynamic Memory Management with Operators new and delete Enables programmers to allocate and deallocate memory for any built-in or user-defined type Performed by operators new and delete For example, dynamically allocating memory for an array instead of using a fixed-size array In C++ char * ptr = new char[size]; delete [] ptr; In C char * ptr = (char *) malloc(size); free(ptr);

10.6 Dynamic Memory Management with Operators new and delete (Cont.) Operator new Allocates (i.e., reserves) storage of the proper size for an object at execution time Calls a constructor to initialize the object Returns a pointer of the type specified to the right of new Can be used to dynamically allocate any fundamental type (such as int or double) or any class type Free store Sometimes called the heap Region of memory assigned to each program for storing objects created at execution time

10.6 Dynamic Memory Management with Operators new and delete (Cont.) Operator delete Destroys a dynamically allocated object Calls the destructor for the object Deallocates (i.e., releases) memory from the free store The memory can then be reused by the system to allocate other objects

10.6 Dynamic Memory Management with Operators new and delete (Cont.) Initializing an object allocated by new Initializer for a newly created fundamental-type variable Example double *ptr = new double( 3.14159 ); Specify a comma-separated list of arguments to the constructor of an object Time *timePtr = new Time( 12, 45, 0 );

Common Programming Error 10.8 Not releasing dynamically allocated memory when it is no longer needed can cause the system to run out of memory prematurely. This is sometimes called a “memory leak.”

10.6 Dynamic Memory Management with Operators new and delete (Cont.) new operator can be used to allocate arrays dynamically Dynamically allocate a 10-element integer array: int *gradesArray = new int[ 10 ]; Size of a dynamically allocated array Specified using any integral expression that can be evaluated at execution time

10.6 Dynamic Memory Management with Operators new and delete (Cont.) Delete a dynamically allocated array: delete [] gradesArray; This deallocates the array to which gradesArray points If the pointer points to an array of objects First calls the destructor for every object in the array Then deallocates the memory If the statement did not include the square brackets ([]) and gradesArray pointed to an array of objects Only the first object in the array would have a destructor call

10.7 static Class Members static data member Only one copy of a variable shared by all objects of a class “Class-wide” information A property of the class shared by all instances, not a property of a specific object of the class Declaration begins with keyword static

10.7 static Class Members (Cont.) static data member (Cont.) Example Video game with Martians and other space creatures Each Martian needs to know the martianCount martianCount should be static class-wide data Every Martian can access martianCount as if it were a data member of that Martian Only one copy of martianCount exists May seem like global variables but they have class scope Can be declared public, private or protected

10.7 static Class Members (Cont.) static data member (Cont.) Fundamental-type static data members Initialized by default to 0 If you want a different initial value, a static data member can be initialized once (and only once) A const static data member of int or enum type Can be initialized in its declaration in the class definition All other static data members Must be defined at file scope (i.e., outside the body of the class definition) Can be initialized only in those definitions static data members of class types (i.e., static member objects) that have default constructors Need not be initialized because their default constructors will be called

10.7 static Class Members (Cont.) static data member (Cont.) Exists even when no objects of the class exist To access a public static class member when no objects of the class exist Prefix the class name and the binary scope resolution operator (::) to the name of the data member Example Martian::martianCount Also accessible through any object of that class Use the object’s name, the dot operator and the name of the member myMartian.martianCount

10.7 static Class Members (Cont.) static member function Is a service of the class, not of a specific object of the class static applied to an item at file scope That item becomes known only in that file The static members of the class need to be available from any client code that accesses the file So we cannot declare them static in the .cpp file—we declare them static only in the .h file.

Software Engineering Observation 10.11 A class’s static data members and static member functions exist and can be used even if no objects of that class have been instantiated.

Function prototype for static member function Outline fig10_21.cpp (1 of 1) Function prototype for static member function static data member keeps track of number of Employee objects that currently exist

Outline (1 of 3) Employee.cpp static data member is defined and initialized at file scope in the .cpp file static member function can access only static data, because the function might be called when no objects exist

Outline (2 of 3) Employee.cpp Dynamically allocating char arrays Non-static member function (i.e., constructor) can modify the class’s static data members Deallocating memory reserved for arrays

Outline Employee.cpp (3 of 3)

Dynamically creating Employees with new Outline fig10_23.cpp (1 of 2) Calling static member function using class name and binary scope resolution operator Dynamically creating Employees with new Calling a static member function through a pointer to an object of the class

Outline Releasing memory to which a pointer points fig10_23.cpp (2 of 2) Disconnecting a pointer from any space in memory

10.7 static Class Members (Cont.) Declare a member function static If it does not access non-static data members or non-static member functions of the class A static member function does not have a this pointer static data members and static member functions exist independently of any objects of a class When a static member function is called, there might not be any objects of its class in memory

Common Programming Error 10.11 Using the this pointer in a static member function is a compilation error.

Chap 11 Operator Overloading

Operator Overloading Another special function return_type operatorsymbol (parameters); Complex operator+ (const Complex c); To use an operator on class objects, that operator must be overloaded. Three exceptions: (=), (&), (,)

Function Summary General Function Special Function return_type function_name (parameter_list); Special Function Constructor Without return value Destructor Without return and parameters Cannot be overloaded Operator Overloading Specific function name

Restrictions on Operator Overloading Cannot change Precedence of operator (order of evaluation) Use parentheses to force order of operators Associativity (left-to-right or right-to-left) Number of operands e.g., & is unary, can only act on one operand Operator ?: cannot be overloaded How operators act on built-in data types (i.e., cannot change integer addition) Cannot create new operators Operators must be overloaded explicitly Overloading + and = does not overload +=

Operator Functions as Class Members vs. Global Functions Must be Overloaded as Member Functions Operators (), [], -> or any assignment operator must be overloaded as a class member function As Member Functions and Global Functions 運算子的左運算元(或單一運算元)是屬該類別的物件成員函式 運算子的左運算元不是該類別的物件全域函式 想存取該類別的private或protected成員friend函式 Operators >> and << 的多載只能是global或friend function. For Commutativity Commutate the object with user-defined class and the data with fundamental type

Notice function prototypes for overloaded operators >> and << (must be global, friend functions) 28

// Fig. 11.4 : PhoneNumber.cpp #include <iomanip> #include "PhoneNumber.h" using namespace std; ostream & operator<<(ostream &output, const PhoneNumber &number){ output << "(" << number.areaCode << ")" << number.exchange << "-" << number.line; return output; // enables cout << a << b << c; } istream & operator>>(istream &input, PhoneNumber &number){ input.ignore(); // skip ( input >> setw(3) >> number.areaCode; input.ignore(2); // skip ) and space input >> setw(3) >> number.exchange; input.ignore(); //skip dash - input >> setw(4) >> number.line; return input; // enbales cin >> a >> b >> c; Allows cout << phone; to be interpreted as: operator<<(cout, phone); Allows cin >> phone; to be interpreted as: operator>>(cin, phone);

Testing overloaded >> and << operators to input and output a PhoneNumber object 30

Exercise 10.8 建立SavingsAccount類別,用static資料成員annualInterestRate儲存帳戶的年利率。類別的每個物件都包含一個private資料成員savingsBalance,指出每位帳戶內的目前存款餘額。請提供成員函式calculateMonthlyInterest,計算每月的存款利息,其計算方式是將balance乘以annualInterestRate再除以12;計算後的利息必須再加上savingsBalance。請提供static成員函式modifyInterestRate,用來設定static annualInterestRate(年利率)的新值。請撰寫一個程式來測試SavingsAccount,產生兩個不同的SavingsAccount物件,其餘額分別為$2000.00和$3000.00。把annualInterestRate的值設為3%,計算每個月的利息,並且印出每位存款者的新餘額。接下來,請將annualInterestRate設定為4%,計算下個月的利息,並印出每個存戶的新存款。

Exercise 10.8 Class Name Public Member Function Private Data Member SavingsAccount Public Member Function SavingsAccount(double); // constructor void calculateMonthlyInterest(); static void modifyInterestRate(double); Private Data Member double savingsBalance; static double annualInterestRate;