Download presentation
Presentation is loading. Please wait.
1
Recitation Course 0603 Speaker: Liu Yu-Jiun
2
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);
3
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
4
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
5
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( ); Specify a comma-separated list of arguments to the constructor of an object Time *timePtr = new Time( 12, 45, 0 );
6
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.”
7
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
8
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
9
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
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
11
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
12
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
13
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.
14
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.
15
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
16
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
17
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
18
Outline Employee.cpp (3 of 3)
19
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
20
Outline Releasing memory to which a pointer points fig10_23.cpp (2 of 2) Disconnecting a pointer from any space in memory
21
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
22
Common Programming Error 10.11
Using the this pointer in a static member function is a compilation error.
23
Chap 11 Operator Overloading
24
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: (=), (&), (,)
25
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
26
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 +=
27
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
28
Notice function prototypes for overloaded operators >> and << (must be global, friend functions) 28
29
// 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);
30
Testing overloaded >> and << operators to input and output a PhoneNumber object
30
31
Exercise 10.8 建立SavingsAccount類別,用static資料成員annualInterestRate儲存帳戶的年利率。類別的每個物件都包含一個private資料成員savingsBalance,指出每位帳戶內的目前存款餘額。請提供成員函式calculateMonthlyInterest,計算每月的存款利息,其計算方式是將balance乘以annualInterestRate再除以12;計算後的利息必須再加上savingsBalance。請提供static成員函式modifyInterestRate,用來設定static annualInterestRate(年利率)的新值。請撰寫一個程式來測試SavingsAccount,產生兩個不同的SavingsAccount物件,其餘額分別為$ 和$ 。把annualInterestRate的值設為3%,計算每個月的利息,並且印出每位存款者的新餘額。接下來,請將annualInterestRate設定為4%,計算下個月的利息,並印出每個存戶的新存款。
32
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;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.