c程序設計(part 3)_第1頁
c程序設計(part 3)_第2頁
c程序設計(part 3)_第3頁
c程序設計(part 3)_第4頁
c程序設計(part 3)_第5頁
已閱讀5頁,還剩59頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領

文檔簡介

1、整理課件面向?qū)ο蟪绦蛟O計(part 3)整理課件多態(tài)n定義n一般含義n某論域中的一個元素可以有多種解釋n作用n提高語言靈活性n實現(xiàn)高層軟件的復用整理課件多態(tài)n程序語言范疇n一名多用 n相同的語言結(jié)構(gòu)可以代表不同類型的實體n類屬 n相同的語言結(jié)構(gòu)可以對不同類型的實體進行操作n面向?qū)ο蟪绦蛟O計具有一種獨特的多態(tài)n一個公共的消息集可以發(fā)送到不同種類的對象,從而得到不同的處理整理課件多態(tài)n函數(shù)重載n在同一個作用域中,相同的標識符可以用于定義不同的函數(shù),但要求這些函數(shù)應擁有不同的參數(shù)(參數(shù)類型或個數(shù))n函數(shù)重載主要用于定義多個功能相同而參數(shù)不同的函數(shù)n在C+中,對重載函數(shù)的綁定采用靜態(tài)綁定,由編譯系統(tǒng)根

2、據(jù)實參與形參的匹配實現(xiàn)整理課件操作符重載n操作符重載n動機n語言提供的操作符只定義了針對基本數(shù)據(jù)類型操作的語義n操作符重載機制提供了對自定義數(shù)據(jù)類型進行操作的語義描述手段n作用n提高程序的可讀性n提高語言的靈活性、可擴充性整理課件操作符重載class Complex double real, imag; public: Complex() real = 0; imag = 0; Complex(double r, double i) real = r; imag = i; Complex add(Complex& x);Complex a(1,2),b(3,4), c;c = a.add(b)

3、;class Complex double real, imag; public:Complex() real = 0; imag = 0; Complex(double r, double i) real = r; imag = i; Complex operator + (Complex& x) Complex temp; temp.real = real+x.real; temp.imag = imag+x.imag; return temp;Complex a(1,2),b(3,4),c;c = a.operator +(b);c = a + b易理解優(yōu)先級結(jié)合性整理課件操作符重載cl

4、ass Complex double real, imag; public:Complex() real = 0; imag = 0; Complex(double r, double i) real = r; imag = i; friend Complex operator + (Complex& c1, Complex& c2);Complex operator + (Complex& c1, Complex& c2) Complex temp; temp.real = c1.real + c2.real; temp.imag = c1.imag + c2.imag; return te

5、mp; Complex a(1,2),b(3,4),c; c = a + b;operator + (a, b)至少包含一個用戶自定義類型至少包含一個用戶自定義類型(new、delete除外)除外)整理課件示例enum Day SUN, MON, TUE, WED, THU, FRI, SAT;void main() Day d=SAT; +d; cout d;Day& operator+(Day& d) return d= (d=SAT)? SUN: Day(d+1); ostream& operator (ostream& o, Day& d)switch (d)case SUN: o S

6、UN endl;break;case MON: o MON endl;break;case TUE: o TUE endl;break;case WED: o WED endl;break;case THU: o THU endl;break;case FRI: o FRI endl;break;case SAT: o SAT endl;break;return o;整理課件操作符重載n可重載的操作符n. .* : ?: n操作符重載基本原則n方式n類成員函數(shù)n帶有類參數(shù)的全局函數(shù)n遵循已有操作符的語法n單目/雙目n優(yōu)先級n結(jié)合性n遵循已有操作符的語義n除操作符=外,重載的操作符可以繼承cla

7、ss A int x; public: A(int i):x(i) void f() void g() ; void (A:*p_f)() ; p_f= A:f; (a.*p_f)();整理課件操作符重載n雙目操作符重載n類成員函數(shù)n格式 operator # ()nthis 隱含n使用 a, b; a # b ; a.operator#(b) ; 整理課件操作符重載n全局函數(shù)n友元 friend operator # (,)n格式 operator # (,) n限制 = () 不能作為全局函數(shù)重載整理課件操作符重載n區(qū)別n成員函數(shù)只需給一個參數(shù),而全局函數(shù)必須給兩個參數(shù)n有時必須用全局函數(shù)

8、重載操作符class CL int count; public: friend CL operator +(int i, CL& a); friend CL operator +(CL& a, int i);;obj + 1010 + obj ?= () 不能作為全局函數(shù)重載 ?整理課件操作符重載n永遠不要重載 & 和 |char *p;if (p != 0) & (strlen(p) 10) if (expressin1 & expression2) if (expression1.operator&(expression2)if (operator &(expression1, expre

9、ssion2)整理課件操作符重載class Rational public :Rational(int,int);private:int n, d;const Rational& operator *(const Rational& r);nreturn Rational(n*r.n, d*r.d);nRational *result = new Rational(n*r.n, d*r.d); return *result;nstatic Rational result; result.n = n*r.n; result.d = d*r.d; return result;w = x*y*zif

10、 (a*b) =(c*d)盡可能讓事情有效率,但不是過度有效率整理課件多態(tài)n單目操作符重載n類成員函數(shù)nthis 隱含n格式 operator # ()n全局函數(shù) operator # ()整理課件多態(tài)na+ vs +an+ 左值class Counter int value; public: Counter() value = 0; Counter& operator +() / +a value+; return *this; Counter operator +(int) /a+ Counter temp=*this; value+; return temp; dummy argumen

11、tprefix operatorpostfix operator整理課件特殊操作符重載n= =n默認賦值操作符重載函數(shù)n逐個成員賦值(member-wise assignment)n對含有對象成員的類,該定義是遞歸的n自定義賦值操作符重載函數(shù)n資源n賦值操作符重載不能繼承賦值操作符重載不能繼承整理課件特殊操作符重載 class A int x,y; char *p; public:A& operator = (A& a);A a, b;a = b;idle pointerx = a.x; y = a.y;delete p; p = new charstrlen(a.p)+1; strcpy(p

12、,a.p); return *this;整理課件特殊操作符重載n避免自我賦值nSample: class stringns = s?nclass A void f(A& a); nvoid f(A&a1, A& a2);nint f2(Derived &rd, Base& rb);nObject identitynContentnSame memory locationnObject identifierclass A public: ObjectID identity() const; .; A *p1,*p2; .p1- identity()= p2- identity()整理課件特殊操作

13、符重載nclass string char *p; public:string(char *p1) p = new char strlen(p1)+1; strcpy(p,p1); char& operator (int i) return pi; virtual string() delete p;string s(“aacd”); s2 = b ;const char operator (int i) const return pi; const string cs(“const”); cs0 = D; ?整理課件特殊操作符重載n多維數(shù)組nclass Array2Dndata(2,3);n

14、data12; ?整理課件class Array2D public:class Array1D public:Array1D(int *p) this-p = p; int& operator (int index) return pindex; const int operator (int index) const return pindex; private:int *p;Array2D(int n1, int n2) p = new intn1*n2; num1 = n1; num2 = n2; virtual Array2D( ) delete p; Array1D operator

15、 (int index) return p+index*num2; const Array1D operator (int index) const return p+index*num2; private:int *p;int num1, num2;proxy classSurrogate 多維int *整理課件特殊操作符重載n smart pointersmart pointern為二元運算符class CPen int m_color; int m_width; public: void setColor(int c) m_color = c; int getWidth() return

16、 m_width; ;class CPanel CPen m_pen; int m_bkColor; public: CPen* operator -() return &m_pen; void setBkColor(int c) m_bkColor =c; ;CPanel c;c-setColor(16); / c.operator-()-setColor(16); /c.m_pen.setColor(16)c-getWidth(); / c.operator-()-getWidth();/c.m_pen.getWidth()CPanel *p=&c;p-setBkColor(10);A a

17、;a-f();a.operator-( ?)重載重載時時按按一元操作符一元操作符重載重載描述描述 a.operator a.operator -()-f()()-f()Prevent memory Leak整理課件特殊操作符重載n( )( ) class Func double para;int lowerBound, upperBound; public:double operator () (double, int, int);Func f;/計算對象f(2.4, 0, 8);整理課件特殊操作符重載n類型轉(zhuǎn)換運算符n基本數(shù)據(jù)類型n自定義類class Rational public :Rat

18、ional(int n1, int n2) n = n1; d = n2; operator double() return (double)n/d; private:int n, d;Rational r(1,2); double x = r; ostream f(“abc.txt”);if (f) .重載 數(shù)值型:如 int整理課件特殊操作符重載nnew 、deleten頻繁調(diào)用系統(tǒng)的存儲管理,影響效率n程序自身管理內(nèi)存,提高效率n方法n調(diào)用系統(tǒng)存儲分配,申請一塊較大的內(nèi)存n針對該內(nèi)存,自己管理存儲分配、去配n通過重載 new 與 delete 來實現(xiàn)n重載的 new 和 delete 是

19、靜態(tài)成員n重載的 new 和 delete 遵循類的訪問控制,可繼承整理課件特殊操作符重載n重載 newnvoid *operator new (size_t size, )n名: operator newn返回類型: void *n第一個參數(shù):size_t(unsigned int)n系統(tǒng)自動計算對象的大小,并傳值給sizen其它參數(shù):可有可無nA * p = new () A , 表示傳給new的其它實參nnew 的重載可以有多個n如果重載了new,那么通過new 動態(tài)創(chuàng)建該類的對象時將不再調(diào)用內(nèi)置的(預定義的)new整理課件特殊操作符重載n重載 deletenvoid operator

20、delete(void *p, size_t size)n名:operator deleten返回類型:voidn第一個參數(shù):void *n被撤銷對象的地址n第二個參數(shù):可有可無;如果有,則必須是size_t 類型n被撤消對象的大小ndelete 的重載只能有一個n如果重載了delete,那么通過delete 撤消對象時將不再調(diào)用內(nèi)置的(預定義的)delete整理課件模板templaten模板n源代碼復用機制n參數(shù)化模塊n對程序模塊(如:類、函數(shù))加上類型參數(shù)類型參數(shù)n對不同類型的數(shù)據(jù)實施相同的操作n多態(tài)的一種形式nC+n類屬函數(shù)n類屬類整理課件模板template functionn類屬函數(shù)

21、template functionn同一函數(shù)對不同類型的數(shù)據(jù)完成相同的操作n宏實現(xiàn)n#define max(a,b) (a)(b)?(a):(b)n缺陷n只能實現(xiàn)簡單的功能n沒有類型檢查n重復計算整理課件模板n函數(shù)重載int max(int,int);double max(double,double);A max(A,A);n缺陷n需要定義的重載函數(shù)太多n定義不全整理課件模板n函數(shù)指針 void sort(void * , unsigned int, unsigned int,int (* cmp) (void *, void *) )n缺陷n需要定義額外參數(shù)n大量指針運算n實現(xiàn)起來復雜n可讀

22、性差template 引入的目標:完全完全清晰清晰整理課件模板n函數(shù)模板void sort(int A, unsigned int num) for (int i=1; inum; i+)for (int j=0; j Aj+1) int t = Aj;Aj = Aj+1;Aj+1 = t; TTtemplate int a100;sort(a,100);double b200;sort(b,200);class C C a300; sort(a,300); 必須重載必須重載操作符操作符 = copy constructor整理課件模板n函數(shù)模板定義了一類重載的函數(shù)n編譯系統(tǒng)自動實例化函數(shù)模板

23、n函數(shù)模板的參數(shù)n可有多個類型參數(shù),用逗號分隔n可帶普通參數(shù)n必須列在類型參數(shù)之后n調(diào)用時需顯式實例化template void f(T1 a, T2 b) . template void f(T a) T tempsize; . f(1);整理課件模板n函數(shù)模板與函數(shù)重載配合使用template T max(T a, T b) return ab?a:b;int x, y, z;double l, m, n;z = max(x,y);l = max(m,n);問題:max(x,m) 如何處理?定義一個max的重載函數(shù):double max(int a, double b) return ab

24、? a : b; 整理課件模板template classn類屬類類定義帶有類型參數(shù)template class Stack T buffer100; public: void push(T x); T pop();template void Stack :push(T x) template T Stack :pop() Stack st1; Stack st2;class Stack int buffer100; public: void push(int x); int pop();void Stack:push(int x) int Stack:pop() Stack st1;顯式實例

25、化整理課件模板n定義了若干個類n顯式實例化n可帶有多個參數(shù)n可帶有普通參數(shù)n逗號分隔n須放在類型參數(shù)之后n類模板中的靜態(tài)成員屬于實例化后的類n不同實例之間不存在共享靜態(tài)成員?靜態(tài)成員?整理課件模板例template class Stack T buffersize; public: void push(T x); T pop();template void Stack :push(T x) template T Stack :pop() Stack st1;Stack st2;整理課件模板n模板是一種代碼復用機制n源代碼復用n實例化:生成具體的函數(shù)/類n函數(shù)模板的實例化n隱式實現(xiàn)n根據(jù)具體模板

26、函數(shù)調(diào)用n類模板的實例化n創(chuàng)建對象時顯式指定n是否實例化模板的某個實例由使用點來決定是否實例化模板的某個實例由使用點來決定;如果未使用到如果未使用到一個模板的某個實例,則編譯系統(tǒng)不會生成相應實例的代碼一個模板的某個實例,則編譯系統(tǒng)不會生成相應實例的代碼整理課件模板nC+中模塊是分別編譯n如果在模塊A中要使用模塊B中定義的某模板的實例,而在模塊B中未使用這個實例,則模塊A無法使用這個實例#include file1.htemplate void S:f() template T max(T x, T y) return xy?x:y;void main() int a,b; max(a,b);

27、S x; x.f();template class S T a; public: void f();#include file1.hextern double max(double,double);void sub() max(1.1,2.2); /Error S x; x.f(); /ErrorC+中模板的完整定義通常出現(xiàn)在頭文件中中模板的完整定義通常出現(xiàn)在頭文件中整理課件Template MetaProgrammingtemplateclass Fib public: enum value = Fib:value + Fib:value ;void main() cout Fib:valu

28、e endl; template class Fib public: enum value = 1 ;template class Fib public: enum value = 1 ;/ calculated at compile time整理課件異常處理n錯誤n語法錯誤n程序書寫不符合語法規(guī)則n編譯系統(tǒng)n邏輯錯誤n程序設計不當造成程序沒有完成預期的功能n測試n異常 Exceptionn運行環(huán)境造成n內(nèi)存不足、文件操作失敗等n異常處理整理課件異常處理n特征n可以預料n無法避免n作用n預見性處理n提高程序魯棒性(Robustness)n問題n發(fā)現(xiàn)異常之處與處理異常之處不一致void f(ch

29、ar *str) ifstream file(str); if (file.fail() /異常處理 int x; file x; 整理課件異常處理n常見處理方法n函數(shù)參數(shù)n返回值n引用參數(shù)n逐層返回n缺陷n程序結(jié)構(gòu)不清楚整理課件異常處理nC+異常處理機制n一種專門、清晰描述異常處理過程的機制n處理機制ntryn監(jiān)控可能造成異常的操作(語句塊)nthrown拋擲異常對象ncatchn捕獲并處理try throw catch ( ) 整理課件異常處理ncatchn類型:異常類型,匹配規(guī)則同函數(shù)重載n變量:存儲異常對象,可省n一個try 語句塊的后面可以跟多個catch 語句塊, 用于捕獲不同類型

30、的異常進行處理void f() . throw 1; . throw 1.0; . throw abcd; . try f(); catch ( int ) /處理throw 1; catch (char * ) /throw abcd 整理課件異常處理n異常處理的嵌套fgh 調(diào)用關(guān)系h() throw 1; /由g捕獲并處理 throw “abcd”; /由 f捕獲并處理g() try h(); catch (int) f() try g(); catch (int) catch (char *) 如果拋擲的異常對象在調(diào)用鏈上沒有給出捕獲,則調(diào)系統(tǒng)的abort作標準異常處理整理課件異常處理n

31、定義異常類n對于派生層次結(jié)構(gòu)的異常處理,要注意catch 塊組中的順序int f() try . throw WrongFormat catch (NonExist) . catch (DiskSeekError) catch (FileErrors) class FileErrors ;class NonExist: public FileErrors ;class WrongFormat: public FileErrors ;class DiskSeekError: public FileErrors ;整理課件異常處理n特例n無參數(shù)thrown將捕獲到的異常對象重新拋擲出去 catch

32、 (int) throw; ncatch() n默認異常處理nCatch exceptions by reference 整理課件I/O 處理n基于函數(shù)庫的I/On基于類庫的I/Oiosistreamifstreamistrstreamostreamofstreamostrstreamiostreamfstreamstrstream整理課件I/O 處理nI/O流庫的三類輸入/輸出操作n控制臺I/O標準I/O設備ncin、cout、cerr、clogn文件I/On字符串I/O整理課件I/O 處理n操作符重載n對自定義類的對象的I/On全局(友元)函數(shù)重載class CPoint2D double

33、 x, y; public: friend ostream& operator (ostream&, CPoint2D &);ostream& operator (ostream& out, CPoint2D& a) out a.x , a.y endl;return out; CPoint2D a;cout a;class CPoint3D: public CPoint2D double z; ;. CPoint3D b; cout b; 只顯示和,而沒顯示ostream& operator (ostream& out, CPoint3D & b) out b.x , b.y , b.z e

34、ndl;return out; friend ostream& operator (ostream &, CPoint3D &);Virtualizing non-member functions整理課件I/O 處理class CPoint2D double x, y;public: virtual void display(ostream& out) out x , y endl; ;ostream& operator (ostream& out, CPoint2D &a) a.display(out); return out; class CPoint3D: public CPoint2D

35、 double z; public: void display(ostream& out) CPoint2D:display(); out , z endl; ;整理課件Virtualizing constructorsnVirtual constructornVirtual functionnConstructornQuestionn【報紙】n文字、圖形TextBlockGraphicListObjectsNewsLetterNLComponentpointers整理課件Virtualizing constructorsclass NLComponent ;class TextBlock :

36、 public NLComponent ;class Graphic : public NLComponent ;class NewsLetter public: NewsLetter(istream& str) while (str) components.push_back(readComponent(str); static NLComponent * readComponent(istream& str); private: list components;NewsLetter(const NewsLetter& rhs) for (list:iterator it=ponent.be

37、gin();it != ponent.end(); +it ) component.push_back( ? );new TextBlock? Graphic?整理課件Virtualizing constructorsnvirtual NLComponent * clone() const = 0;nvirtual TextBlock * clone() const return new TextBlock(*this); nvirtual Graphic * clone() const return new Graphic (*this); nNewsLetter:NewsLetter( const NewsLetter& rhs) for ( list:iterator it=ponent.begin();it != ponent.end(); +it ) component.push_back(*it)-clone(); 整理課件Know what functions C+ silently writes and callsnclass Empty ; nclass Empty Empty();Empty(const Empty&);Empty();Empty& operator=(const Empty&);Empty *operator &(

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論