Copyright © 2002 Pearson Education, Inc. Slide 1.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

1 生物計算期末作業 暨南大學資訊工程系 2003/05/13. 2 compare f1 f2  只比較兩個檔案 f1 與 f2 ,比完後將結果輸出。 compare directory  以兩兩比對的方式,比對一個目錄下所有檔案的相 似程度。  將相似度很高的檔案做成報表輸出,報表中至少要.
6-1 指標簡介 6-2 指標與陣列 6-3 動態配置記憶體 6-4 本章綜合練習
布林代數的應用--- 全及項(最小項)和全或項(最大項)展開式
Introduction to Java Programming Lecture 13 Classes I OO Programming.
建立使用案例敘述 --Use Case Narrative
學習C++的基本語法 認識關鍵字與識別字的不同 學習程式碼偵錯的流程 學習如何提高程式的可讀性
: A-Sequence 星級 : ★★☆☆☆ 題組: Online-judge.uva.es PROBLEM SET Volume CIX 題號: Problem D : A-Sequence 解題者:薛祖淵 解題日期: 2006 年 2 月 21 日 題意:一開始先輸入一個.
Reference, primitive, call by XXX 必也正名乎 誌謝 : 部份文字取於前輩 TAHO 的文章.
如何將數字變成可用之資訊 現代化資料處理與應用概念. 如何將數字變成可用之資訊 人最容易接受的訊息是圖像化資訊。 在一堆數字中,要進行比較分析,一般會使用表格形 式計算與分析。 所以一般我們會將數字依關聯性, 轉換成表格計算與分析。 此表格一般稱試算表或稱表格。 再將結果轉換為圖表,進行比較與分析。
What is static?. Static? 靜態 ? class Test { static int staticX; int instanceX; public Test(int var1, int var2) { this.staticX = var1; this.instanceX =
建立靜態資料成員 關鍵字: static 靜態資料成員不屬於特定物件,而是該類物件 所共同擁有的,可做為類別範圍裡的靜態變數。
: OPENING DOORS ? 題組: Problem Set Archive with Online Judge 題號: 10606: OPENING DOORS 解題者:侯沛彣 解題日期: 2006 年 6 月 11 日 題意: - 某間學校有 N 個學生,每個學生都有自己的衣物櫃.
第一章 變數、常數及資料型態. 變數 C 程式語言的變數名稱 第一個字必須是英文字母或底線 (_) 之後可以是數字, 英文字母或底線 (_) 不可以是保留字 例: Num (Ο) _score (Ο) C&C (X) 8num (X)
: ShellSort ★★☆☆☆ 題組: Problem D 題號: 10152: ShellSort 解題者:林一帆 解題日期: 2006 年 4 月 10 日 題意:烏龜王國的烏龜總是一隻一隻疊在一起。唯一改變烏龜位置 的方法為:一隻烏龜爬出他原來的位置,然後往上爬到最上方。給 你一堆烏龜原來排列的順序,以及我們想要的烏龜的排列順序,你.
JAVA 程式設計與資料結構 第二章 JAVA 程式基本概念及操作. 第一個程式 /* * 這是第一個程式 (FirstP.java) */ class FirstP{ public static void main(String args[]){ System.out.println("Whatever.
STAT0_sampling Random Sampling  母體: Finite population & Infinity population  由一大小為 N 的有限母體中抽出一樣本數為 n 的樣 本,若每一樣本被抽出的機率是一樣的,這樣本稱 為隨機樣本 (random sample)
第 13 章 常數、靜態成員與朋友關 係 13-1 常數物件與成員 13-1 常數物件與成員 13-2 物件成員與巢狀類別 13-2 物件成員與巢狀類別 13-3 靜態成員資料與函數 13-3 靜態成員資料與函數 13-4 朋友關係 13-4 朋友關係.
1. 假設以下的敘述為一未提供 “ 捷徑計算 ” 能力的程式段,試用程 式設計的技巧,使此敘述經此改 寫的動作後,具有與 “ 捷徑計算 ” 之 處理方法相同之處理模式。 if and then E1 else E2 endif.
例外處理. 內 容 大 綱 例外的產生 捕捉例外 丟出例外 例外的產生 (1/4) 一般常見的執行時期錯誤包括整數除法分母為 0(divide by zero) ,陣列索引值越限 (array index out of range) ,輸入輸出錯誤 (I/O error) 、檔案 不存在或無法存取.
JAVA 程式設計與資料結構 第十四章 Linked List. Introduction Linked List 的結構就是將物件排成一列, 有點像是 Array ,但是我們卻無法直接經 由 index 得到其中的物件 在 Linked List 中,每一個點我們稱之為 node ,第一個 node.
MATLAB 程式設計 第 11 章 多維陣列 多維陣列的定義 在 MATLAB 的資料型態中,向量可視為 一維陣列,矩陣可視二維陣列,對於維 度 (Dimensions) 超過 1 的陣列則均可視 為「多維陣列」 (Multidimesional Arrays , 簡稱 N-D Arrays)
第 18 章 名稱空間與例外處理 18-1 名稱空間 18-1 名稱空間 18-2 例外處理 18-2 例外處理.
程式註解說明. 2 程式註解格式 塊狀註解 對檔案、 class 、 method 、資料結構、一段程式 …. 等程式區塊 做說明。 第一行的開頭必需為 “/*” 且沒有其他文字,最後一行的開頭 必需以 “*/” 做為結束,在中間每一行的開頭都必需是一個 “*” 。 單行註解 佔據一整行的說明。 以.
Introduction to Java Programming Lecture 5: Using Java Classes : String & Math Spring 2009.
Chapter 13 塑模靜態觀點:物件圖 Static View : Object Diagram.
Introduction to Java Programming Lecture 17 Abstract Classes & Interfaces.
Copyright © 2002 Pearson Education, Inc. Slide 1.
7 陣列與搜尋 7.1 陣列 一般資料變數 宣告一維陣列 起始一維陣列 7-4
Chapter 20 塑模動態觀點:狀態圖 Statechart Diagram. 學習目標  說明狀態圖的目的  定義狀態圖的基本記號  展示狀態圖的建構  定義活動、內部事件及遞延事件的狀態 圖記號.
Hung-Hsiang WuWindows Processing Design1 Chapter 3 基本觀念 變數宣告與型態 特殊運算子符號 字串與數值的轉換 類別與物件的觀念 建立新的專案 WinMain 程式進入點 Include Header File.
: Fast and Easy Data Compressor ★★☆☆☆ 題組: Problem Set Archive with Online Judge 題號: 10043: Fast and Easy Data Compressor 解題者:葉貫中 解題日期: 2007 年 3.
: Multisets and Sequences ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 11023: Multisets and Sequences 解題者:葉貫中 解題日期: 2007 年 4 月 24 日 題意:在這個題目中,我們要定義.
:Nuts for nuts..Nuts for nuts.. ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 10944:Nuts for nuts.. 解題者:楊家豪 解題日期: 2006 年 2 月 題意: 給定兩個正整數 x,y.
資料結構實習-一 參數傳遞.
6-2 認識元件庫與內建元件庫 Flash 的元件庫分兩種, 一種是每個動畫專 屬的元件庫 (Library) ;另一種則是內建元 件庫 (Common Libraries), 兩者皆可透過 『視窗』功能表來開啟, 以下即為您說明。
1/46 物件導向的字串處理 內建的完整類別 string 具有豐富的 成員函數,能以物件導向的語法處 理字串,讓程式設計者免除空間安 排及安插結尾符號等瑣碎的工作。 內建的完整類別 string 具有豐富的 成員函數,能以物件導向的語法處 理字串,讓程式設計者免除空間安 排及安插結尾符號等瑣碎的工作。
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2008.
4 堆疊與佇列 4.1 前言 四種基本的資料結構 (可儲存資料的容器) 陣列 (Array)、串列(List): 最基本
: Beautiful Numbers ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 11472: Beautiful Numbers 解題者:邱經達 解題日期: 2011 年 5 月 5 日 題意: 若一個 N 進位的數用到該.
Section 4.2 Probability Models 機率模式. 由實驗看機率 實驗前先列出所有可能的實驗結果。 – 擲銅板:正面或反面。 – 擲骰子: 1~6 點。 – 擲骰子兩顆: (1,1),(1,2),(1,3),… 等 36 種。 決定每一個可能的實驗結果發生機率。 – 實驗後所有的實驗結果整理得到。
函式 Function Part.2 東海大學物理系‧資訊教育 施奇廷. 遞迴( Recursion ) 函式可以「呼叫自己」,這種動作稱為 「遞迴」 此程式的執行結果相當於陷入無窮迴圈, 無法停止(只能按 Ctrl-C ) 這給我們一個暗示:函式的遞迴呼叫可以 達到部分迴圈的效果.
JAVA 程式設計與資料結構 第二十章 Searching. Sequential Searching Sequential Searching 是最簡單的一種搜尋法,此演 算法可應用在 Array 或是 Linked List 此等資料結構。 Sequential Searching 的 worst-case.
資料結構實習-二.
演算法 8-1 最大數及最小數找法 8-2 排序 8-3 二元搜尋法.
Windows Processing Design1 Chapter 1 C/C++ 概論 畫面輸出與鍵盤輸入 程式流程 程式流程的迴圈 函數的基礎 指標與陣列 字串 類別 利用 BCB 開發程式.
845: Gas Station Numbers ★★★ 題組: Problem Set Archive with Online Judge 題號: 845: Gas Station Numbers. 解題者:張維珊 解題日期: 2006 年 2 月 題意: 將輸入的數字,經過重新排列組合或旋轉數字,得到比原先的數字大,
第 17 章 樣板 17-1 樣板的基礎 17-1 樣板的基礎 17-2 樣板函數 17-2 樣板函數 17-3 樣板類別 17-3 樣板類別 17-4 非型態參數的樣板類別 17-4 非型態參數的樣板類別 17-5 樣板類別的繼承 17-5 樣板類別的繼承 17-6 特化樣板與靜態成員 17-6 特化樣板與靜態成員.
Chapter 10 m-way 搜尋樹與B-Tree
: Function Overloading ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 11032:Function Overloading 解題者:許智祺 解題日期: 2007 年 5 月 8 日 題意:判對輸入之數字是否為.
JAVA 程式設計與資料結構 第十六章 Hash Tables. Introduction Hash Tables 結構為一個 Array ,稱之為 Bucket array 。 如果想要新增一個物件,要根據這個物件的特性 將其加入 Hash Table 內。 Bucket Array 用 A 來代替,其.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009.
5 重複迴圈 5.1 增減運算符號 增量運算符號 減量運算符號
函式 Function 東海大學物理系‧資訊教育 施奇廷. 函式簡介 當程式越來越大、越複雜時,程式的維護、 除錯會變得更困難,此時必須引入函式來 簡化程式或將程式分段,將程式重複的部 分改寫為函式,將程式「模組化」 這種作法有下列優點:節省程式發展的時 間、邏輯容易瞭解、程式容易除錯、可分 工合作完成程式.
Visual C++重點複習.
資料結構實習-六.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2010.
第8章 字串與陣列 8-1一維陣列的處理 8-2 字串處理 8-3 多維陣列的處理 8-4 動態陣列與參數傳遞 8-5 陣列排序與搜尋.
Introduction to Java Programming Lecture 16 Super and Sub Classes.
: Finding Paths in Grid ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11486: Finding Paths in Grid 解題者:李重儀 解題日期: 2008 年 10 月 14 日 題意:給一個 7 個 column.
著作權所有 © 旗標出版股份有限公司 第 14 章 製作信封、標籤. 本章提要 製作單一信封 製作單一郵寄標籤.
幼兒行為觀察與記錄 第八章 事件取樣法.
McGraw-Hill/Irwin © 2003 The McGraw-Hill Companies, Inc.,All Rights Reserved. 肆 資料分析與表達.
第 8 章 記憶體指標. 8.0 變數、數值、位址 8.1 指標與變數 對 C++ 語言而言,指標( pointers )是存放 變數或陣列的位址,因此也可以藉由指標 間接取得變數或陣列中的值。 對 C++ 語言而言,指標( pointers )是存放 變數或陣列的位址,因此也可以藉由指標 間接取得變數或陣列中的值。
Chapter 3 Visual Basic.Net Visual Basic, like most programming languages, uses variables for storing values. Variables have a name (the word you use to.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
Constructors and Other Tools
Presentation transcript:

Copyright © 2002 Pearson Education, Inc. Slide 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Copyright © 2002 Pearson Education, Inc. Slide 17 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 的方法

Copyright © 2002 Pearson Education, Inc. Slide 18 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 等級, 所以不能直接 呼叫

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

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

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

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

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

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); // 建立建構子,傳入四個資料參數 };

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

Copyright © 2002 Pearson Education, Inc. Slide 26 建構子定義於類別內 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; };

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

Copyright © 2002 Pearson Education, Inc. Slide 28 建構子定義於類別外 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; } 類別名稱 :: 類別名稱

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

Copyright © 2002 Pearson Education, Inc. Slide 30 成員起始序 (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){ } 宣告建構子的同時,以 : 開始, 宣告每個資料成員的初值 編輯其他初使值,若 不需要時就空著

Copyright © 2002 Pearson Education, Inc. Slide 31 成員起始序 (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; } 宣告建構子的同時,以 : 開始, 宣告每個資料成員的初值 另外編輯其他初使值

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

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

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

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

Copyright © 2002 Pearson Education, Inc. Slide 36 作業 _4_ 建立物件 物件:學生名單 class NameList{ private: string _list[10][2]; public: string get_Name(string num); string get_Num(string name); void set_Name(string num,string name); void Display(); NameList(string List[10][2]); };

Copyright © 2002 Pearson Education, Inc. Slide 37 string _list[10][2]; 功能:學生名單存取學生學號和學生姓名 可以存 10 位學生的學號和姓名 _list[i][0]: 第 i 位學生的學號 _list[i][1]: 第 i 位學生的姓名

Copyright © 2002 Pearson Education, Inc. Slide 38 NameList 的功能 string get_Name(string num): 輸入學號 num ,查詢學生姓名 string get_Num(string name) : 輸入學生姓名 name ,查詢學生學號 void set_Name(string num,string name): 更改學號為 num 的學生姓名,更改為 name 如 :namelist.set_Name(“ ”,” 劉家佑 ”) 將學號為 ” ” 的學生姓名改為叫 ” 劉家佑 ” void Display(): 列印出學生名單

Copyright © 2002 Pearson Education, Inc. Slide 39 建構子 NameList(string List[10][2]); 輸入一個 List[10][2] 的陣列, 將資料存到 _list[10][2] 陣列中

Copyright © 2002 Pearson Education, Inc. Slide 40 主程式 學生名單功能界面請參考網路上的主程式內容, 請不要修改主程式的內容, 只需要將 NameList 物件的程式捕齊

Copyright © 2002 Pearson Education, Inc. Slide 41 String C++ 所提供的字串類別 使用 string 類別時,必須載入 string 標頭檔 #include

Copyright © 2002 Pearson Education, Inc. Slide 42 String 的六種建構子 string() string(const charT* s); string(const charT* s, size_type n); string(size_type n, charT c); string(const basic_string& str, size_type pos=0, size_type n=npos); string(InputIterators begin, InputIterators end);

Copyright © 2002 Pearson Education, Inc. Slide 43 String 的建構方式 string s0 ; -- 宣告一個沒有資料的字串 string s1(“HI~Everybody”); -- 利用字串建立物件 string s2(s1); -- 利用 s1 字串類別建立 s2 字串 string s3(s1,3,9);-- 利用 s1 字串物件第 3 個字之後 9 個字元建立 s3 字串物件 string s4(5,’!’); -- 建立五個 ! 的字串 string s6=s1; -- 複製 s1 字串物件給 s6

Copyright © 2002 Pearson Education, Inc. Slide 44 string(InputIterators begin, InputIterators end) char p1[12]=“HI~Everybody”; string s5(p1+3,p1+12); //s5 字串由 p1 陣列中第 3 個字串到第 12 個字串組成  s5=“Everybody”;

Copyright © 2002 Pearson Education, Inc. Slide 45 字串的指派、互換、移除 、 插入與截取 函數用途使用範例說明 assign 將字串指派給 另外一個字串 s2.assign(s1) 將 s1 指派給 s2 swap 互換 s1 和 s2 s2.swap(s1) 將 s1 和 s2 字串 互換 erase 將字串中一些 字元移除 s1.erase(3,5) 將字串中第 3 個 字元之後的 5 個 字元都移除 insert 將字串插入 s1.insert(2,”HI”) 將 ”HI” 字串插 入 s1 的第 2 個字 元後

Copyright © 2002 Pearson Education, Inc. Slide 46 字串的指派、互換、移除 、 插入與截 取 函數用途使用範例說明 substr 截取字串中的 字元 s1.substr(3,5) 截取 s1 第 3 個字 元後 5 個字元

Copyright © 2002 Pearson Education, Inc. Slide 47 string s0; string s1(“HI~Everybody”); string s2(s1,3,9); s0.assign(s1); cout<<"s0="<<s0<<endl; cout<<"s2="<<s2<<endl; s0.swap(s2); cout<<"s0="<<s0<<endl; cout<<"s2="<<s2<<endl; s0=“HI~Everybody” s0=“” s2=“Everybody” s0=“Everybody” S2=“HI~Everybody”

Copyright © 2002 Pearson Education, Inc. Slide 48 s2.erase(3,5); cout<<"s2="<<s2<<endl; s2.insert(3,"No"); cout<<"s2="<<s2<<endl; s2=s0.substr(5,4); cout<<"s2="<<s2<<endl; s0=“Everybody” s2=“HI~Everybody” s2=“HI~body” s2=“HI~Nobody” s2=“body”

Copyright © 2002 Pearson Education, Inc. Slide 49 比較字串中的字元 -compare compare— 比較兩字串的順序大小,且是根據 英文字母排列的順序比較 且是大寫字母大於小寫字母  s1.compaer(s2) 若 s1 排列順序在 s2 前面,則回傳值將小於 0 若 s1 排列順序和 s2 相同,則回傳值將等於 0 若 s1 排列順序在 s2 之後,則回傳值將大於 0

Copyright © 2002 Pearson Education, Inc. Slide 50 比較字串中的字元 -compare string s0("Everybody"); string s1("HI~Everybody"); string s2("EverybodY"); string s3(s0); cout<<s0.compare(s1)<<endl; cout<<s0.compare(s2)<<endl; cout<<s0.compare(s3); Everybody HI~Everybody Everybody EverybodY Everybody

Copyright © 2002 Pearson Education, Inc. Slide 51 比較字串中的字元 -compare 比較 s1,s2 兩個字串是否相等 s1.compare(s2)  看這值是否為 0 if(s1.compare(s2)==0)  代表 s1 和 s2 的字串相等

Copyright © 2002 Pearson Education, Inc. Slide 52 尋找與置換字串中的字元 函數用途使用範例說明 find 尋找字串中 的字元 s1.find(“ing”) 尋找 s1 中是 否存在 ing 字 串, 並傳回起 始字元的索 引值 repla ce 置換字串 s1.replace(3,2,”ed”) 將 s1 字串中 第 4 個後 2 個 字元換成 ed

Copyright © 2002 Pearson Education, Inc. Slide 53 replace 和 find 並用,直接找尋置換的字串 s1.replace(s1.find( 想要換掉的字串 ), 置換字串長度, 置換字串 ) s1.replace(s1.find(“ing”),2,”ed”); 例子 2: string s1(“HI~Everybody”); s1.replace(s1.find(“Every”),3,”Any”);  s1 變為 “Hi~Anybody”

Copyright © 2002 Pearson Education, Inc. Slide 54 取得字串資訊 函數用途使用範例說明 size() 傳回字串的長 度 ( 字元個數 ) s1.size() 傳回 s1 的 字串長度 max_size() 傳回可宣告最 大字串的長度 s1.max_size() 傳回 s1 可 能容納的 最大字元 數 empty() 若為空字串, 則傳回真 s1.empty() s1 是否為 空字串

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

Copyright © 2002 Pearson Education, Inc. Slide 56 STL (Standard Template Library) 標準樣版程式庫 : 將設計程式裡經常用到的基本資料結構與演算 法,建立為可供程式設計師套用的程式庫 STL 裡提供許多容器,每一種容器就是一種儲 存資料的方法,可以在這容器中放入任何型別 的資料,或是自行定義的類別。

Copyright © 2002 Pearson Education, Inc. Slide 57 vector 可以當做智慧型的陣列,在記憶體中佔有一塊 連續的空間。 和陣列的相異處: (1) vector 是動態處理記憶體大小,宣告時不會 被要求宣告固定的儲存空間。 (2) 可以存取個種類型資料,包括自行定義的類 別。

Copyright © 2002 Pearson Education, Inc. Slide 58 vector 的使用 必須載入 vector 標頭檔 -- #include 宣告 vector -- vector 變數名稱 資料型態 --vector 容器內欲儲存的資料型態 變數名稱 -- 運用 vector 容器宣告之物件名稱

Copyright © 2002 Pearson Education, Inc. Slide 59 vector 容器在記憶體中儲存方法 前端 末端

Copyright © 2002 Pearson Education, Inc. Slide 60 vector 的成員函數 名稱用途 插入與刪除 push_back 在容器末端增加元素 pop_back 在容器末端刪除元素 insert 在容器中間插入元素 erase 刪除容器中間的元素 clear 清除容器內的元素 其他重要的函式 size 傳回目前容器中的元素個數 empty 若容器內無元素傳回 true, 反之傳回 false

Copyright © 2002 Pearson Education, Inc. Slide 61 vector 的成員函數 名稱用途 其他重要的函式 size 傳回目前容器中的元素個數 empty 若容器內無元素傳回 true, 反之傳回 false begin 傳入容器前端的位置 end 傳入容器後端的位置

Copyright © 2002 Pearson Education, Inc. Slide 62 宣告儲存 int 型態的 vector vector v1; v.push_back(1);  存入 1 到 vector[0] 裡 v.push_back(2);  存入 2 到 vector[1] 裡 v.push_back(3);  存入 3 到 vector[2] 裡 v.insert(v.begin()+1,4);  將 4 插入 1 的位置 前端 末端 1234

Copyright © 2002 Pearson Education, Inc. Slide 63 新增 vector 內儲存的資料 新增 vector 內第 i 個位置的資料 v.insert(v.begin()+i, 新增的資料 ) 新增 vector 末端的資料 v.push_back( 新增的資料 )

Copyright © 2002 Pearson Education, Inc. Slide 64 刪除 vector 內儲存的資料 刪除 vector 內第 i 個位置的資料 v.erase(v.begin()+i) 刪除 vector 末端的資料 v.pop_back() 清除容器內所有資料 v.clear()

Copyright © 2002 Pearson Education, Inc. Slide 65 修改 vector 內儲存的資料 修改 vector 內第 i 個位置的資料 v[i]= 修改的資料

Copyright © 2002 Pearson Education, Inc. Slide 66 列印 vector 內的所有資料 for(int i=0;i<v.size();i++)  i 小於 v 的容量大小 cout<<v[i]<<endl;  直接列印 v[i] 的值

Copyright © 2002 Pearson Education, Inc. Slide 67 vector 儲存自行定義的類別 class people{ }; 若自行定義了 people 類別 int main() { vector namelist;  可以存取 people 物件 }

Copyright © 2002 Pearson Education, Inc. Slide 68 vector 儲存自行定義的類別 vector NameList; people John(“John”,22,175.5,64.5);  建立 John 物件 people Mary("Mary",23,165.5,48.5);  建立 Mary 物件 NameList.push_back(John);  存入 John NameList.push_back(Mary);  存入 Mary

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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