Download presentation
Presentation is loading. Please wait.
1
Recitation Course 0520 Speaker: Liu Yu-Jiun
2
Reference: C++ How to Program 6e
Destructors A special member function Name is the tilde character (~) followed by the class name, e.g., ~Time Called implicitly when an object is destroyed For example, this occurs as an automatic object is destroyed when program execution leaves the scope in which that object was instantiated Does not actually release the object’s memory It performs termination housekeeping Then the system reclaims the object’s memory So the memory may be reused to hold new objects 波浪符號表示解構子與建構子是相對的 離開物件的使用域時,系統會自動呼叫物件的解構子。不代表釋放了物件的記憶體空間,要到結束之後,系統才會回收物件佔用的空間,給其他物件使用。 Reference: C++ How to Program 6e
3
Reference: C++ How to Program 6e
9.7 Destructors (Cont.) Receives no parameters and returns no value May not specify a return type—not even void A class may have only one destructor Destructor overloading is not allowed If the programmer does not explicitly provide a destructor, the compiler creates an “empty” destructor 解構子沒有參數也沒有傳回值,而且一個類別只能有一個解構子,也不能overloading。跟建構子相同,使用者沒寫解構子,系統也會預設一個空的。 Reference: C++ How to Program 6e
4
9.8 When Constructors and Destructors Are Called
Called implicitly by the compiler Order of these function calls depends on the order in which execution enters and leaves the scopes where the objects are instantiated Generally, Destructor calls are made in the reverse order of the corresponding constructor calls However, Storage classes of objects can alter the order in which destructors are called 物件的儲存類別會影響解構子的呼叫順序 Reference: C++ How to Program 6e
5
9.8 When Constructors and Destructors Are Called (Cont.)
For an automatic local object Constructor is called when that object is defined Corresponding destructor is called when execution leaves the object’s scope For automatic objects Constructors and destructors are called each time execution enters and leaves the scope of the object Automatic object destructors are not called if the program terminates with an exit or abort function Reference: C++ How to Program 6e
6
9.8 When Constructors and Destructors Are Called (Cont.)
For a static local object Constructor is called only once When execution first reaches where the object is defined Destructor is called when main terminates or the program calls function exit Destructor is not called if the program terminates with a call to function abort Global and static objects are destroyed in the reverse order of their creation Reference: C++ How to Program 6e
7
Prototype for destructor
Reference: C++ How to Program 6e
8
Defining the class’s destructor
Reference: C++ How to Program 6e
9
Reference: C++ How to Program 6e
#include <iostream> #include "CreagAndDestroy.h" using namespace std; void create(void); CreateAndDestroy first(1, "(global before main)"); int main(){ cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy second(2, "(local automatic in main)"); static CreateAndDestroy third(3, "(local static in main)"); create(); cout << "\nMAIN FUNCTION: EXECTION RESUMES" << endl; CreateAndDestroy fourth(4, "(local automatic in main)"); cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl; return 0; } void create(void){ cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy fifth(5, "(local automatic in create)"); static CreateAndDestroy sixth(6, "(local static in create)"); CreateAndDestroy seventh(7, "(local automatic in create)"); cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl; Reference: C++ How to Program 6e
10
Reference: C++ How to Program 6e
11
9.8 When Constructors and Destructors Are Called (Cont.)
For objects defined in global scope Constructors are called before any other function (including main) in that file begins execution The corresponding destructors are called when main terminates Function exit Forces a program to terminate immediately Does not execute the destructors of automatic objects Often used to terminate a program when an error is detected Function abort Performs similarly to function exit But forces the program to terminate immediately without allowing the destructors of any objects to be called Usually used to indicate an abnormal termination of the program 全域物件的建構子呼叫時間甚至比main function還早。 Main function終止的時候會呼叫相對應的解構子。 Exit:不會呼叫自動物件的解構子,程式發生執行錯誤時,利用exit function來終止程式。 Abort:不會呼叫任何物件的解構子,程式不正常結束執行。 Reference: C++ How to Program 6e
12
Reference: C++ How to Program 6e
9.9 Time Class Case Study: A Subtle Trap—Returning a Reference to a private Data Member Returning a reference to an object Alias for the name of an object An acceptable lvalue that can receive a value May be used on the left side of an assignment statement If a function returns a const reference That reference cannot be used as a modifiable lvalue One (dangerous) way to use this capability A public member function of a class returns a reference to a private data member of that class Client code could alter private data Same problem would occur if a pointer to private data were returned Reference: C++ How to Program 6e
13
Reference: C++ How to Program 6e
#include <iostream> using namespace std; class Time{ public: Time(int = 0 , int = 0, int = 0); void setTime(int, int, int); int getHour(); int &badSetHour(int); private: int hour; int minute; int second; }; Time::Time(int hr, int min, int sec){ setTime(hr, min, sec); } void Time::setTime(int h, int m, int s){ hour = (h >= 0 && h < 24) ? h : 0; minute = (m >= 0 && m < 60) ? m : 0; second = (s >= 0 && s < 60) ? s : 0; int Time::getHour(){ return hour; Figure 9.14~9.15 Reference: C++ How to Program 6e
14
Reference: C++ How to Program 6e
int &Time::badSetHour(int hh){ hour = (hh >= 0 && hh < 24) ? hh : 0; cout << "the address of hour is " << &hour << endl; return hour; } int main(){ Time t; int &hourRef = t.badSetHour(20); cout << "hourRef's content: " << hourRef << endl; cout << "hourRef's address: " << &hourRef << endl; hourRef = 30; cout << "\nInvalid hour after modification: " << t.getHour() << endl; t.badSetHour(12) = 74; cout << t.getHour() << endl; system("pause"); return 0; Figure 9.15~9.16 hourRef hour 74 12 20 30 Reference: C++ How to Program 6e
15
Result of Previous Code
the address of hour is 0x23ff60 the content of hourRef: 20 the address of hourRef: 0x23ff60 Invalid hour after modification: 30 Another invalid hour seeting: 74 Reference: C++ How to Program 6e
16
9.10 Default Memberwise Assignment
Assignment operator (=) Can be used to assign an object to another object of the same type Each data member of the right object is assigned to the same data member in the left object Can cause serious problems when data members contain pointers to dynamically allocated memory Reference: C++ How to Program 6e
17
Reference: C++ How to Program 6e
Outline Date.h (1 of 1) Reference: C++ How to Program 6e
18
Reference: C++ How to Program 6e
Outline Date.cpp (1 of 1) Reference: C++ How to Program 6e
19
Outline fig09_19.cpp (1 of 1) Memberwise assignment assigns data members of date1 to date2 date2 now stores the same date as date1 Reference: C++ How to Program 6e
20
9.10 Default Memberwise Assignment (Cont.)
Copy constructor Enables pass-by-value for objects Used to copy original object’s values into new object to be passed to a function or returned from a function Compiler provides a default copy constructor Copies each member of the original object into the corresponding member of the new object (i.e., memberwise assignment) Also can cause serious problems when data members contain pointers to dynamically allocated memory Reference: C++ How to Program 6e
21
Chap 10
22
const object and const member function
object declaring const class_name object_name; Function prototype return_type function_name ( p1, p2, ...) ; const 3 1 2 const const void help (const char * const p1); Reference: C++ How to Program 6e
23
const object and const member function (cont.)
const member functions const objects are only allowed to call const member function Member functions declared const are not allowed to modify the object A function is specified as const both in its prototype and in its definition const declarations are not allowed for constructors and destructors Reference: C++ How to Program 6e
24
const object and const member function (cont.)
const and reference data member不能使用賦值運算子(=),所以設定const資料成員的初始值得用成員初始值列表(member initializer list)。 Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {} const成員函式不可以更動任何成員資料的值。所以,如果成員函式不會更動資料成員的值,可以將成員函式設定為const。 const成員函式只能呼叫其它const成員函式。 Reference data member的話,得給一個變數名稱。 Reference: C++ How to Program 6e
25
10.3 Composition: Objects as Members of Classes
Sometimes referred to as a has-a relationship A class can have objects of other classes as members Example class 機翼{ public: 機翼(int, int); void 轉彎(); int 修正飛行姿勢(int); private: int 寬度; int 長度; }; class 飛機{ public: 飛機(機翼, 機翼, int); private: 機翼 左機翼; 機翼 右機翼; int 載客數; }; int main(){ 機翼 big(3, 5); 飛機 747(big, big, 600); } 三次的機翼建構子呼叫,第一次是呼叫通用建構子,第二、三次是呼叫預設複製建構子;反之,也有三次的機翼解構子呼叫。 Reference: C++ How to Program 6e
26
Reference: C++ How to Program 6e
Constructor Difference between default and general constructor Default Time (int = 0, int = 0, int = 0); Time () {hour = 0, minute = 0, second = 0} General Time (int, int, int); Reference: C++ How to Program 6e
27
10.4 friend Functions and friend Classes
friend function of a class Defined outside that class’s scope Not a member function of that class Yet has the right to access the non-public (and public) members of that class Standalone functions or entire classes may be declared to be friends of a class Reference: C++ How to Program 6e
28
10.4 friend Functions and friend Classes (Cont.)
To declare a function as a friend of a class: Provide the function prototype in the class definition preceded by keyword friend To declare a class as a friend of a class: Place a declaration of the form friend class ClassTwo; in the definition of class ClassOne All member functions of class ClassTwo are friends of class ClassOne 所有在classTwo的成員函式都是classOne的夥伴函式 Reference: C++ How to Program 6e
29
10.4 friend Functions and friend Classes (Cont.)
Friendship is granted, not taken For class B to be a friend of class A, class A must explicitly declare that class B is its friend Friendship relation is neither symmetric nor transitive If class A is a friend of class B, and class B is a friend of class C, you cannot infer that class B is a friend of class A, that class C is a friend of class B, or that class A is a friend of class C It is possible to specify overloaded functions as friends of a class Each overloaded function intended to be a friend must be explicitly declared as a friend of the class Reference: C++ How to Program 6e
30
Outline fig10_15.cpp (1 of 2) friend function declaration (can appear anywhere in the class) Reference: C++ How to Program 6e
31
Outline fig10_15.cpp (2 of 2) friend function can modify Count’s private data Calling a friend function; note that we pass the Count object to the function Reference: C++ How to Program 6e
32
Reference: C++ How to Program 6e
Using the this Pointer Outline fig10_17.cpp (1 of 2) Reference: C++ How to Program 6e
33
Outline fig10_17.cpp (2 of 2) Implicitly using the this pointer to access member x Explicitly using the this pointer to access member x Using the dereferenced this pointer and the dot operator Reference: C++ How to Program 6e
34
Cascaded member-function calls
Outline Time.h (1 of 2) set functions return Time & to enable cascading Reference: C++ How to Program 6e
35
Reference: C++ How to Program 6e
Outline Time.h (2 of 2) Reference: C++ How to Program 6e
36
Outline Time.cpp (1 of 3) Returning dereferenced this pointer enables cascading Reference: C++ How to Program 6e
37
Reference: C++ How to Program 6e
Outline Time.cpp (2 of 3) Reference: C++ How to Program 6e
38
Reference: C++ How to Program 6e
Outline Time.cpp (3 of 3) Reference: C++ How to Program 6e
39
Reference: C++ How to Program 6e
Outline fig10_20.cpp (1 of 2) Cascaded function calls using the reference returned by one function call to invoke the next ((t.setHour(18)).setMinute(30)).setSecond(22); ((t).setMinute(30)).setSecond(22); ((t)).setSecond(22); Note that these calls must appear in the order shown, because printStandard does not return a reference to t Reference: C++ How to Program 6e
40
Reference: C++ How to Program 6e
Outline fig10_20.cpp (2 of 2) Reference: C++ How to Program 6e
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.