Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2002 Pearson Education, Inc. Slide 1.

Similar presentations


Presentation on theme: "Copyright © 2002 Pearson Education, Inc. Slide 1."— Presentation transcript:

1 Copyright © 2002 Pearson Education, Inc. Slide 1

2 Copyright © 2002 Pearson Education, Inc. Slide 2 Chapter 7 Created by Frederick H. Colclough, Colorado Technical University Constructors and Other Tools

3 Copyright © 2002 Pearson Education, Inc. Slide 3 Learning Objectives  Constructors  Definitions  Calling  More Tools  const parameter modifier  Inline functions  Static member data  Vectors  Introduction to vector class

4 Copyright © 2002 Pearson Education, Inc. Slide 4 物件函式 建立類別 建立物件 訊息 — 呼叫物件的成員函數

5 Copyright © 2002 Pearson Education, Inc. Slide 5 建立類別 定義類別 宣告資料成員 定義成員函數

6 Copyright © 2002 Pearson Education, Inc. Slide 6 定義類別 class 類別名稱 { 定義類別成員 }; 完成類別定義, 不要忘 了加上結尾符號 ;

7 Copyright © 2002 Pearson Education, Inc. Slide 7 class people { private: string name; public: void say_hello() }; 定義 people 類別 宣告 people 類別的 資料成員 完成類別定義, 不要忘 了加上結尾符號 ;

8 Copyright © 2002 Pearson Education, Inc. Slide 8 將函數內容定義於類別內 class people { private: string name; public: void say_hello() { cout<<" Hello to You~."<<endl; } };

9 Copyright © 2002 Pearson Education, Inc. Slide 9 將函數內容定義於類別外 傳回型態 型態名稱 :: 成員函數名稱 ( 傳入參數 ) { 函數內容 …… }

10 Copyright © 2002 Pearson Education, Inc. Slide 10 將函數內容定義於類別外 class people { private: string name; public: void say_hello() }; people :: say_hello() { cout<<" Hello to You~."<<endl; } 類別名稱 方法名稱 ( 函數名稱 )

11 Copyright © 2002 Pearson Education, Inc. Slide 11 建立物件 宣告方式 類別名稱 物件名稱 ; 例如: people John;

12 Copyright © 2002 Pearson Education, Inc. Slide 12 成員存取 物件名稱. 資料成員名稱 物件名稱. 成員函數名稱 ( 傳入變數 )

13 Copyright © 2002 Pearson Education, Inc. Slide 13 建立物件 int main() { people John; John.say_hello(); return 0; } 依據 people 類別 建立 John 物件 呼叫 John 物件的 成員函數

14 Copyright © 2002 Pearson Education, Inc. Slide 14 存取權限的控制 存取權限意義可存取的對象使用說明 public 公開級 程式內任何敘述均可 存取 以資訊隱藏的角度, 類別的資料成員應 該避免為 public private 私有級 1. 該類別的成員函數 2. 該類別的 friend 類別 或 friend 類別 以資訊隱藏的角度, 類別的資料應該盡 量定義為 private ,以 保護資料成員不被 任意存取 protected 保護級 1. 類別的成員函數 2. 繼承該類別之衍生 類別的成員函數 protected 等級介於 public 與 private 之間

15 Copyright © 2002 Pearson Education, Inc. Slide 15 存取權限 class 類別名稱 // 開始定義類別 { private: …… 宣告 private 等級成員的敘述 public: …… 宣告 public 等級成員的敘述 protected: …… 宣告 public 等級成員的敘述 }; // 類別定義結束

16 Copyright © 2002 Pearson Education, Inc. Slide 16 class people { public: string name; void say-hello() { cout<<" Hello to You~."<<endl; } people(string text); }; people::people(string text) { name=text; } int main() { people Student("John"); cout<<Student.name<<" : "; Student.say-hello(); return 0; } people 的建構子 呼叫 Student 的名字 呼叫 say-hello 的方法

17 Copyright © 2002 Pearson Education, Inc. Slide 17 class people { private: string name; public: void say_hello() { cout<<" Hello to You~."<<endl; } people(string text); }; people::people(string text) { name=text; } int main() { people Student("John"); cout<<Student.name<<" : "; Student.say_hello(); return 0; } name 是 private 類別 因為 name 是 private 等級, 所以不能直接 呼叫

18 Copyright © 2002 Pearson Education, Inc. Slide 18 class people { private: string name; public: void say_hello() { cout<<" Hello to You~."<<endl; } people(string text); string getName(); }; people::people(string text) { name=text; } string people::getName() { return name; } int main() { people Student("John"); cout<<Student.getName()<<" : "; Student.say_hello(); return 0; } 呼叫 people 的 getName() 方法 ( 函數 ) 利用 people 類別的 getName() 方法 ( 函數 ) 回傳 name

19 Copyright © 2002 Pearson Education, Inc. Slide 19 定義類別時的不能初始化資料 class people { private: string name; int age=1; double hight,weight; public: void say_hello() void show_information(); string getName(); }; 定義類別時的不 能初始化資料 利用建構子初始化 物件的初值

20 Copyright © 2002 Pearson Education, Inc. Slide 20 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

21 Copyright © 2002 Pearson Education, Inc. Slide 21 Constructor Definitions  Constructors defined like any member function  Except: 1. Must have same name as class 2. Cannot return a value; not even void!

22 Copyright © 2002 Pearson Education, Inc. Slide 22 建構子定義於類別內 class people { private: string name; int age; double hight,weight; public: people(string p_name,int p_age,double p_hight, double p_weight); // 建立建構子,傳入四個資料參數 };

23 Copyright © 2002 Pearson Education, Inc. Slide 23 建構子定義於類別內 class people{ private: string name; int age; double hight,weight; public: people(string p_name,int p_age,double p_hight,double p_weight) { name=p_name; age=p_age; hight=p_hight; weight=p_weight; };

24 Copyright © 2002 Pearson Education, Inc. Slide 24 建構子定義於類別外 class people { private: string name; int age; double hight,weight; public: people(string p_name,int p_age,double p_hight, double p_weight); // 建立建構子,傳入四個資料參數 };

25 Copyright © 2002 Pearson Education, Inc. Slide 25 建構子定義於類別外 people::people(string p_name,int p_age,double p_hight,double p_weight) { name=p_name; age=p_age; hight=p_hight; weight=p_weight; } 類別名稱 :: 類別名稱

26 Copyright © 2002 Pearson Education, Inc. Slide 26 成員起始序 (Memeber initialization list) 類別名稱 ( 參數列 ) : 資料成員 ( 初值 ) ,資料成員 ( 初值 )….. { ……} people::people(string p_name,int p_age,double p_hight,double p_weight) :name(p_name),age(p_age),hight(p_hight),weight(p_weight){ } 宣告建構子的同時,以 : 開始, 宣告每個資料成員的初值 編輯其他初使值,若 不需要時就空著

27 Copyright © 2002 Pearson Education, Inc. Slide 27 成員起始序 (Memeber initialization list) 類別名稱 ( 參數列 ) : 資料成員 ( 初值 ) ,資料成員 ( 初值 )….. { ……} people::people(string p_name,int p_age,double p_hight,double p_weight) :name(p_name),age(p_age) { hight = p_hight * 0.9; weight = p_hight * 1.2; } 宣告建構子的同時,以 : 開始, 宣告每個資料成員的初值 另外編輯其他初使值

28 Copyright © 2002 Pearson Education, Inc. Slide 28 物件的產生 _ 建構子 利用類別的成員函數,執行資料的初值設定。 建構子的存取權限等級不會被宣告為 private , 否則宣告物件時,建構子將無法被呼叫。 建構子大部分被定義為 public ,某些情形是 定義為 protected 。 建構子沒有回傳值。

29 Copyright © 2002 Pearson Education, Inc. Slide 29 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; }

30 Copyright © 2002 Pearson Education, Inc. Slide 30 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!

31 Copyright © 2002 Pearson Education, Inc. Slide 31 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  7date2.month  5 date1.dat  4date2.day  5

32 Copyright © 2002 Pearson Education, Inc. Slide 32 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!

33 Copyright © 2002 Pearson Education, Inc. Slide 33 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

34 Copyright © 2002 Pearson Education, Inc. Slide 34 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

35 Copyright © 2002 Pearson Education, Inc. Slide 35 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

36 Copyright © 2002 Pearson Education, Inc. Slide 36 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’

37 Copyright © 2002 Pearson Education, Inc. Slide 37 Class with Constructors Example  [Call-out to Display 7.1, p. 262; Long example, but important for overall explanation]

38 Copyright © 2002 Pearson Education, Inc. Slide 38 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!

39 Copyright © 2002 Pearson Education, Inc. Slide 39 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

40 Copyright © 2002 Pearson Education, Inc. Slide 40 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

41 Copyright © 2002 Pearson Education, Inc. Slide 41 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

42 Copyright © 2002 Pearson Education, Inc. Slide 42 Class Type Member Variables  Class member variables can be any type  Including objects of other classes!  Type of class relationship  Powerful OOP principle  Need special notation for constructors  So they can call ‘back’ to member object’s constructor

43 Copyright © 2002 Pearson Education, Inc. Slide 43 Class Member Variable Example  [Call-out Display 7.3, p. 275-276]

44 Copyright © 2002 Pearson Education, Inc. Slide 44 Parameter Passing Methods  Efficiency of parameter passing  Call-by-value  Requires copy be made  Overhead  Call-by-reference  Placeholder for actual argument  Most efficient method  Negligible difference for simple types  For class types  clear advantage  Call-by-reference desirable  Especially for ‘large’ data, like class types

45 Copyright © 2002 Pearson Education, Inc. Slide 45 The const Parameter Modifier  Large data types (typically classes)  Desirable to use pass-by-reference  Even if function will not make modifications  Protect argument  Use constant parameter  Also called constant call-by-reference parameter  Place keyword const before type  Makes parameter ‘read-only’  Attempts to modify result in compiler error

46 Copyright © 2002 Pearson Education, Inc. Slide 46 Use of const  All-or-nothing  If no need for function modifications  Protect parameter with const  Protect ALL such parameters  This includes class member function parameters

47 Copyright © 2002 Pearson Education, Inc. Slide 47 Inline Functions  For non-member functions:  Use keyword inline in function declaration and function heading  For class member functions:  Place implementation (code) for function IN class definition  automatically inline  Use for very short functions only  Code actually inserted in place of call  Eliminates overhead  More efficient, but only when short!

48 Copyright © 2002 Pearson Education, Inc. Slide 48 Inline Member Functions  Member function definitions  Typically defined separately, in different file  Can be defined IN class definition  Makes function ‘in-line’  Again: use for very short functions only  More efficient  If too long  actually less efficient!

49 Copyright © 2002 Pearson Education, Inc. Slide 49 Static Members  Static member variables  All objects of class ‘share’ one copy  One object changes it  all see change  Useful for ‘tracking’  How often a member function is called  How many objects exist at given time  Place keyword static before type

50 Copyright © 2002 Pearson Education, Inc. Slide 50 Static Functions  Member functions can be static  If no access to object data needed  And still ‘must’ be member of the class  Make it a static function  Can then be called outside class  From non-class objects:  E.g.: Server::getTurn();  As well as via class objects  Standard method: myObject.getTurn();  Can only use static data, functions!

51 Copyright © 2002 Pearson Education, Inc. Slide 51 Static Members Example  [Call-out Display 7.6, p. 287]

52 Copyright © 2002 Pearson Education, Inc. Slide 52 Vectors  Vector Introduction  Recall: arrays are fixed size  Vectors: ‘arrays that grow and shrink’  During program execution  Formed from Standard Template Library (STL)  Using template class

53 Copyright © 2002 Pearson Education, Inc. Slide 53 Vector Basics  Similar to array:  Has base type  Stores collection of base type values  Declared differently:  Syntax: vector  Indicates template class  Any type can be ‘plugged in’ to Base_Type  Produces ‘new’ class for vectors with that type  Example declaration: vector v;

54 Copyright © 2002 Pearson Education, Inc. Slide 54 Vector Use  vector v;  ’v is vector of type int’  Calls class default constructor  Empty vector object created  Indexed like arrays for access  But to add elements:  Must call member function push_back  Member function size()  Returns current number of elements

55 Copyright © 2002 Pearson Education, Inc. Slide 55 Vector Example  [Call-out Display 7.7, p. 292]

56 Copyright © 2002 Pearson Education, Inc. Slide 56 Vector Efficiency  Member function capacity()  Returns memory currently allocated  Not same as size()  Capacity typically > size  Automatically increased as needed  If efficiency critical:  Can set behaviors manually  v.reserve(32); //sets capacity to 32  v.reserve(v.size()+10); //sets capacity to 10 more than size

57 Copyright © 2002 Pearson Education, Inc. Slide 57 Summary 1  Constructors: automatic initialization of class data  Called when objects are declared  Constructor has same name as class  Default constructor has no parameters  Should always be defined  Class member variables  Can be objects of other classes  Require initialization-section

58 Copyright © 2002 Pearson Education, Inc. Slide 58 Summary 2  Constant call-by-reference parameters  More efficient than call-by-value  Can inline very short function definitions  Can improve efficiency  Static member variables  Shared by all objects of a class  Vector classes  Like: ‘arrays that grow and shrink’


Download ppt "Copyright © 2002 Pearson Education, Inc. Slide 1."

Similar presentations


Ads by Google