c指針和動態(tài)內(nèi)存分配PPT課件_第1頁
c指針和動態(tài)內(nèi)存分配PPT課件_第2頁
c指針和動態(tài)內(nèi)存分配PPT課件_第3頁
c指針和動態(tài)內(nèi)存分配PPT課件_第4頁
c指針和動態(tài)內(nèi)存分配PPT課件_第5頁
已閱讀5頁,還剩89頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

1、Lecture 9: Pointers and Dynamic Memory (指針和動態(tài)內(nèi)存分配)(指針和動態(tài)內(nèi)存分配) Learn C+ through English and Chinese第1頁/共94頁2Chapter Nine: Pointers and Dynamic Memory (指針和(指針和動態(tài)內(nèi)存分配)動態(tài)內(nèi)存分配) Variable address (變量的地址)Pointer variables (指針變量)The dereference operator *(解引用運算符*)Using const with pointers (使用const修飾指針變量) Poi

2、nters and one-dimensional arrays(指針和一維數(shù)組) Pointers and multi-dimensional arrays (指針和多維數(shù)組) 第2頁/共94頁3 Pointers to structures (指向結(jié)構(gòu)體的指針) Pointers to class objects (指向類對象的指針) Pointers as function arguments(指針變量作為函數(shù)實參) Dynamic memory allocation(動態(tài)內(nèi)存分配) Chapter Nine: Pointers and Dynamic Memory (指針和動態(tài)內(nèi)(指針

3、和動態(tài)內(nèi)存分配)存分配) 第3頁/共94頁49.1 Variable address(變量地址變量地址) Every variable object used in a C+ program is stored in a specific place in memory. Each location in memory has a unique address, in the same way that every house in a street has a unique address.(在C+程序中使用的每個變量和對象,都存儲在內(nèi)存中特定的存儲單元中。每個存儲單元都有唯一的地址,就像街

4、道旁的每個房子都有唯一的地址一樣。)第4頁/共94頁5Variable address(變量地址變量地址) 內(nèi)存空間的訪問方式 通過變量名訪問 通過地址訪問 地址運算符:&例:int var;則&var 表示變量var在內(nèi)存中的起始地址第5頁/共94頁6 #include #include using namespace std ; void main() int var1 = 1 ; float var2 = 2 ; cout var1 has a value of var1 and is stored at &var1 endl ; cout var2 has a

5、value of var2 and is stored at &var2 endl ; 第6頁/共94頁77.1.1 地址與指針地址與指針程序中程序中: int i; float k; 內(nèi)存中每個字節(jié)有一個編號內(nèi)存中每個字節(jié)有一個編號-地址地址.2000200120022005內(nèi)存內(nèi)存02003ik為其分配內(nèi)存單元為其分配內(nèi)存單元變量變量是對程序中數(shù)據(jù)是對程序中數(shù)據(jù)及存儲空間的抽象及存儲空間的抽象第7頁/共94頁89.2 Pointer variables(指針變量指針變量) A pointer variable is a variable that holds the address

6、 of another variable.(指針變量是存放另一變量地址的變量) data_type* variable_name; int* int_ptr; float* float_ptr; 其中,其中,“* *”表示后面聲明的變量是指針類型的變表示后面聲明的變量是指針類型的變量。指針變量一旦被賦值,我們就說該指針變量有量。指針變量一旦被賦值,我們就說該指針變量有了指向。了指向?!皵?shù)據(jù)類型數(shù)據(jù)類型”可以是任意類型,指的是指可以是任意類型,指的是指針?biāo)赶虻膶ο箢愋?,這說明了指針?biāo)赶虻膬?nèi)存針?biāo)赶虻膶ο箢愋?,這說明了指針?biāo)赶虻膬?nèi)存單元可以用于存放什么類型的數(shù)據(jù),我們稱之為指單元可以用于存

7、放什么類型的數(shù)據(jù),我們稱之為指針的類型。針的類型。區(qū)分:區(qū)分:int * p1, * p2; 與與 int *p1, p2;第8頁/共94頁9Pointer variables(指針指針 聲明聲明 例:例:int i; int *i_pointer=&i; 指向整型變量的指針指向整型變量的指針 使用使用 例例1: i=3; 例例2: *i_pointer=3; 語法形式語法形式 存儲類型存儲類型 數(shù)據(jù)類型數(shù)據(jù)類型 *指針名初始地址;指針名初始地址; 例:例: int *pa=&a;20003i_pointer*i_pointeri2000注意事項注意事項 用變量地址作為初值時,

8、該變量必須在指針初始化之用變量地址作為初值時,該變量必須在指針初始化之前已說明過,且變量類型應(yīng)與指針類型一致。前已說明過,且變量類型應(yīng)與指針類型一致。 可以用一個已賦初值的指針去初始化另一可以用一個已賦初值的指針去初始化另一 個指針變量。個指針變量。 第9頁/共94頁10說明:說明: 在指針變量定義中,在指針變量定義中,*是一個是一個說明符說明符,它表明其后的變量,它表明其后的變量是指針變量,如在是指針變量,如在 int * p; 語句中,語句中,p是指針變量是指針變量,而不要而不要認為認為“*p”是指針變量;是指針變量; 指針變量定義時指定的指針變量定義時指定的數(shù)據(jù)類型數(shù)據(jù)類型不是指針變量本

9、身的數(shù)據(jù)不是指針變量本身的數(shù)據(jù)類型,而是指針變量所指向的對象(或稱目標(biāo))的數(shù)據(jù)類類型,而是指針變量所指向的對象(或稱目標(biāo))的數(shù)據(jù)類型,型,指針變量指針變量只能指向只能指向定義時所規(guī)定類型的變量;定義時所規(guī)定類型的變量; 定義后值定義后值不確定,而指針變量一旦被賦值,就有了有效的,而指針變量一旦被賦值,就有了有效的指向?qū)ο?;指向?qū)ο螅?指針變量并不固定指向一個變量,可指向指針變量并不固定指向一個變量,可指向同類型同類型的的不同變不同變量量; 指針變量和普通變量的共同點是:它們都能存放數(shù)據(jù),而指針變量和普通變量的共同點是:它們都能存放數(shù)據(jù),而又有自己的地址。不同的是:普通變量中直接存放通常意又有自

10、己的地址。不同的是:普通變量中直接存放通常意義下的數(shù)據(jù),而指針變量中存放的是義下的數(shù)據(jù),而指針變量中存放的是地址地址。第10頁/共94頁11.2000200420062005整型變量整型變量i10變量變量i_pointer2001200220032000指針指針指針變量指針變量 變量的變量的內(nèi)容內(nèi)容 變量的變量的地址地址指針變量指針變量變量變量變量地址變量地址( (指針指針) )變量值變量值指向指向地址存入地址存入指針變量指針變量指針變量和指針?biāo)赶虻淖兞康膮^(qū)別:指針變量和指針?biāo)赶虻淖兞康膮^(qū)別:對于:對于:int i=10, * i_pointer = &i; 變量的變量的地址地址

11、變量的變量的內(nèi)容內(nèi)容指針變量是用于存放內(nèi)存單元地址指針變量是用于存放內(nèi)存單元地址的變量,指針?biāo)赶虻淖兞渴侵羔樧兞康淖兞?,指針?biāo)赶虻淖兞渴侵羔樧兞恐兴4娴膬?nèi)存地址對應(yīng)的變量。中所保存的內(nèi)存地址對應(yīng)的變量。 第11頁/共94頁129.3 the dereference operator *(解引用運算符解引用運算符*) The dereference operator * is used to access the value of a variable, whose address is stored in a pointer.(解引用運算符*用于訪問指針變量所指向的存儲單元的內(nèi)容。)in

12、t i=10, * i_pointer =&i;i_pointer = &i = &(*i_pointer)i = *i_pointer = *(&i) i_pointer-指針變量,它的內(nèi)容是地址量指針變量,它的內(nèi)容是地址量*i_pointer-指針的指針的目標(biāo)變量目標(biāo)變量,它的內(nèi)容是數(shù)據(jù),它的內(nèi)容是數(shù)據(jù)&i_pointer- -指針變量占用內(nèi)存的地址指針變量占用內(nèi)存的地址第12頁/共94頁13#include using namespace std;main() int var =1; int* ptr; ptr=&var; / ptr co

13、ntains the address of var cout ptr contains ptr endl ; cout “*ptr contains *ptr endl ; prt contains 0012FF88*ptr contains 1 第13頁/共94頁14#includeusing namespace std;int main()int *p1,*p2,*p,a,b;cinab;p1=&a;p2=&b;if(ab)p=p1;p1=p2;p2=p;couta=ab=bendl;coutmax=*p1min=*p2endl;return 0;第14頁/共94頁159.

14、4 Using const with pointers(使用使用const修飾指針變量修飾指針變量) When defining a pointer, the pointer itself, the value it points to or both can be made constant. The position of const in the definition determines which of these apply.(定義指針變量時,指針變量本身、指針變量所指向的數(shù)據(jù)都可以聲明為常量。變量定義中的const的位置決定了誰被聲明為常量。)第15頁/共94頁16 int i=

15、3,j=4;(a) const int* p=&i;/*p is a constant but p is not. *p=5; / Illegal: cannot change i using p. i=5; / Legal: i is not a constant. p=&j; / Legal: p now point to j. *p=4(b) int const* p=&i; / *p is a constant; p is not.(c) int* const p=&i; / p is a constant; *p is not. *p=5; /Lega

16、l: *p can be changed. i=5 p=&j; /Illegal: p is a constant.(d) const int* const p=&i; / both p and *p are constants. *p=5; /Illegal: *p is a constant. p=&j; /Illegal: p is a constant.第16頁/共94頁17指針與常量指針與常量 指向常變量的指指向常變量的指針針 不能通過指針來改變所指對象的值,但指針本身可以改變,可以指向另外的對象。例: const int n2=5;const int *pn

17、= &n2; *pn=6; /錯誤例:const char *name1=“John”; char s =“abc”; name1=s; 對 *name1=1; 錯第17頁/共94頁18定義指向常變量的指針變量形式:const 類型名 * 指針變量名如:const char *ptr;(1)如果一個變量已經(jīng)被聲明為常變量,只能用指向常變量的指針變量指向它,而不能用一般的指針變量去指向它。如:const char c=“boy”;const char*pp=c;char *p2=c; /不合語法。第18頁/共94頁19(2)指向常變量的指針變量除了可以指向常變量外,還可以指向未被聲明為

18、const型的變量,此時不能通過指針變量改變該變量的值。char c1=a;const char *p;p=&c1;*p=b; /錯誤c1=b;第19頁/共94頁20指針與常量指針與常量 常量指常量指針針 若聲明指針常量,則指針本身的值不能被改變。 但是它指向的整型變量是可以改變的。 例:int n1=3; const int n2=5;int *const pn= &n1; pn=&n2; /錯誤*pn=6; /正確例: char * const name1=“John”; name1=“abc”; 錯第20頁/共94頁21例例 指向常量的指針做形參指向常量的指針做形

19、參#includeconst int N=6;void print(const int *p,int n);void main() int arrayN; for(int i=0;iarrayi; print(array,N);第21頁/共94頁22void print(const int *p, int n) cout*p; for(int i=1;in;i+) cout.*(p+i); coutendl;1 2 3 4 5 .5.6 第22頁/共94頁239.5 Pointers and one-dimensional arrays Ponters and arrays a

20、re directly related to one another . In c+ ,the name of an array is equivalent to the address of the first element of the array. The name of an array ,therefore ,is a pointer to the first element of the array . (指針和數(shù)組是相互聯(lián)系的。在C+中,數(shù)組名代表數(shù)組的首地址。因此,數(shù)組名即為指向數(shù)組第一個元素的指針。) int a5; a &a0 a+1&a1 As the

21、name of an array is a pointer to the first element of the array, the dereference operator * can be used to access the elements of the array.第23頁/共94頁24Pointers and one-dimensional arrays指向數(shù)組元素的指針int a10;int *p;p=&a0;/把a0元素的地址賦給指針變量p, 也就是使指針變量p指向a數(shù)組的第0號元素。它等價于p=a;/它表示把數(shù)組首元素的地址賦給 *p=&a0;它

22、等價于int *p; p=&a0;也可以定義為 int*p=a;*p=1;第24頁/共94頁25Pointers and one-dimensional arrays如果指針變量p已經(jīng)指向數(shù)組中得一個元素,則P+1指向同一數(shù)組中得下一個元素。int array 10=1,2,3,4,5,6,7,8,9,10,*p;當(dāng)p=array時下面的等價關(guān)系成立:p=array=&array0/表示數(shù)組元素的首地址p+i=array+i=&arrayi;/表示第i個數(shù)組元素的地址*(p+i)=*(array+i)=arrayi/表示第i個數(shù)組元素指向數(shù)組的的指針變量也可以帶下標(biāo),所

23、以p+i和pi是一樣的、第25頁/共94頁26引用數(shù)組元素引用數(shù)組元素可以有三種方法:(1)下標(biāo)法: 數(shù)組名下標(biāo) a1(2)指針變量法:*指針變量 *(P+i)(3)首地址法:*(首地址+位移量 ) *(array+i)第26頁/共94頁27如果先使指針變量p指向數(shù)組a的首地址(p=a)則:(1)p+ 使p指向下一個元素,即a1,用*p可以得到下一個元素a1的值,(2)*p+ 先得到p指向的變量的值,然后再使P得值加1,使p指向下一個元素,for(p=a;pa+10;)cout*p+; (3)*(p+)和*(+P)不同,后者是先使P加1,在求*P的值。(4)(*p)+表示P所指向的元素值加1.

24、 第27頁/共94頁28#include using namespace std ;main() int a5 = 10, 13 , 15 , 11, 6 ; for ( int i = 0; i 5; i+ ) cout Element i is *( a + i ) endl ; Element 0 is 10 Element 1 is 13 Element 2 is 15 Element 3 is 11 Element 4 is 6 第28頁/共94頁29 Although the name of an array is a pointer to the first element of

25、 the array, you cannot change its value; this is because it is a constant pointer.(雖然數(shù)組名是指向數(shù)組第一個元素的指針,但是由于它是一個常量指針,因此它的值是不能改變的。) int a10; float numbers100; a+; number+=2;Pointers and one-dimensional arrays第29頁/共94頁30 You can assign the name of an array to a pointer variable of the same type. int a5;

26、 int * p; p=a; / valid :assiqnment of a constant to a variable a+ ; / Invalia: the value of a costant cannot change. p+; / Valid:p is a variable. p now points to element 1 of the array a . p-; / Valid :point to element 1 of the array a . p +=10 ;/ Valid. But p is outside the range of the array a . /

27、 so *p is underfined . A common error. p=a -1; / Valid , but p is outside the ranger of the array .Pointers and one-dimensional arrays第30頁/共94頁31 A constant may be added to or subtancted from the value of a pointer. allowing access to different memory to locations. Hower ,not all arithmeic operation

28、s are permissible on poniters .For example ,the multiplication of two pointers is illegal,because the result would not be a valid memory address.(通過將指針變量加上或減去一個常量,可以使它指向不同的存儲單元。但是,并非所有的算術(shù)運算符都可以應(yīng)用于指針。例如,兩個指針相乘是非法的,因為相乘的結(jié)果可能不是一個有效的內(nèi)存地址。)Pointers and one-dimensional arrays第31頁/共94頁32分別用三種方式訪問數(shù)組中的所有元素分別

29、用三種方式訪問數(shù)組中的所有元素void main( ) int i, array10= 1,2,3,4,5,6,7,8,9,10 , *p; coutNO1: ; for( i=0; i10; i+) coutarrayi= arrayi ; coutnNO2:n; for( i=0; i10; i+) cout*(array+“i)=*(array+i) ; coutnNO3(1)n; for( p=array, i=0; i10;i+) cout*(p+“i)=*(p+i) ; coutnNOs(2)n; for( p=array; parray+10; p+) cout*p+=“*p ;

30、 coutn; 第32頁/共94頁33 A two-dimensional array is stored as an array of arrays. This means that a is a one-dimensional array whose elements are themselves a one-dimensional arrays of integers . As with one-dimensonal array ,the name of a two dimensional array is pointer to the first element of the arra

31、y .Therefore a is equivalent to &a 0 , a 0 is itself an array of two intergers,which means that a 0 is equivalent to &a00 . Pointers and multi-dimensional arrays第33頁/共94頁34a+2a0a00a03a10a13a20a23a1a2aa+1a0+0a0+3a1+3a2+3int a34; a13 *(a1+3) *(*(a+1)+3)第34頁/共94頁35#includeusing namespace std;in

32、t main()int a34=1,3,5,7,9,11,13,15,17,19,21,23;int *p;for(p=a0;pa0+12;p+)cout*p ;cout成員名成員名例:例: struct stu date, *pstu = &date; 則:則:pstu -num 等價于等價于 (*pstu).num第37頁/共94頁38指向結(jié)構(gòu)體變量的指針指向結(jié)構(gòu)體變量的指針#includeusing namespace std;int main() struct student int num; string name; char sex; float score; ;stude

33、nt stu;student*p=&stu;stu.num=10301;=WangFun;stu.sex=f;stu.score=89.5;coutstu.num stu.sex stu.scoreendl;cout(*p).num (*p).name (*p).score (*p).sex成員名 -指向運算符P-n得到P指向的結(jié)構(gòu)體變量中的成員n的值。p-n+得到p指向的結(jié)構(gòu)體變量中成員n的值,用完改值后使它加1.+p-n得到p指向的結(jié)構(gòu)體變量中的成員n的值,并使之加1,然后再使用它。第39頁/共94頁40用指向結(jié)構(gòu)體變量的指針作實參#include

34、#includeusing namespace std;struct studentint num;string name;float score3;stu=12345,lifung,67.5,89,78.5;int main()void print(student *);student *pt=&stu;print(pt);return 0;void print(student*p)coutnum “name “score0“score1“score2成員名第42頁/共94頁43Class Time public: int hour; int minute;int sex; void

35、 get_time();Void Time:get_time() couthour“:”minute“:”sexhour p1所指向的對象中的hour成員,(*p1).get_time 調(diào)用p1所指向的對象中的get_time 函數(shù)P1-get_time 調(diào)用p1所指向的對象中的get_time 函數(shù)第44頁/共94頁45例例 對象指針應(yīng)用舉例對象指針應(yīng)用舉例void main( ) Point A(5,10); Point *ptr; ptr=&A; int x; x=ptr-GetX( ); coutxendl;第45頁/共94頁46Example#include #include

36、 #include bank_ac.h#include bank_ac.cppusing namespace std ;main() bank_account ac ; / ac is a bank_account object. bank_account* ac_ptr ; / ac_ptr is a pointer to a bank_account. ac_ptr = &ac ; / ac_ptr contains the address of the object ac. ac_ptr - deposit( 100 ) ; ac_ptr - display_balance()

37、; ac-ptr - deposit (100) ; ( *ac_ptr) .deopsit(100); 第46頁/共94頁47 9.9 Pointers as funtion arguments Like any data type, pointers can be used as function arguments.第47頁/共94頁48#include using namespace std ;void swap_vals( float* val1, float* val2 ) ; main() float num1 , num2 ; cout num1 ; cin num2 ; if

38、 ( num1 num2 ) swap_vals( &num1, &num2 ) ; cout The numbers in order are num1 and num2 endl ; void swap_vals( float* ptr1, float* ptr2 ) float temp = *ptr1 ; *ptr1=*ptr2;*ptr2=temp;第48頁/共94頁499.10 Dynamic memory allocation C+ has the ability to allocate memory while a program is executing. T

39、his is done by using the memory allocation operator new.第49頁/共94頁50 Dynamic memory allocation動態(tài)申請內(nèi)存操作符 newnew 類型名T(初值列表)功能:在程序執(zhí)行期間,申請用于存放T類型對象的內(nèi)存空間,并依初值列表賦以初值。結(jié)果值:成功:T類型的指針,指向新分配的內(nèi)存。失?。?(NULL)第50頁/共94頁51new運算符的例子;new int;/開辟一個存放整數(shù)的存儲空間,返回一個指向該存儲空間的地址(即指針)new int(100);/開辟一個存放整數(shù)的存儲空間,并指定該整數(shù)的初值為100,返回一

40、個指向該存儲空間的地址(即指針),new char10;/開辟一個存放字符數(shù)組的(包含10個元素)空間,返回首元素的地址。new int54;/開辟一個存放二維整型數(shù)組(大小為5*4)的空間,返回首元素的地址。float *p =new float();/開辟一個存放單精度數(shù)的空間,并指定該實數(shù)的初值是,將返回的該空間的地址賦給指針變量p。第51頁/共94頁52釋放內(nèi)存操作符釋放內(nèi)存操作符deletedelete 運算符使用的一般格式為:delete 指針P功能:釋放指針P所指向的內(nèi)存。P必須是new操作的返回值。delete p;new char10;如果把 new返回的指針付給指針變量pt

41、,則用 delete pt;/在指針變量前面加一對方括號,表示是對數(shù)組空間的操作。第52頁/共94頁53#include#includeusing namespace std;struct studentchar * name;int num;char sex;int main() student*p;p=new student;p-name=wang Fun;p-num=10123;p-sex=m;coutnameendlnumendlsexendl;delete p;return 0;第53頁/共94頁54例例 動態(tài)存儲分配舉例動態(tài)存儲分配舉例#include struct date in

42、t month; int day; int year;第54頁/共94頁55void main( ) int index, *point1, *point2; point1 = &index; *point1 = 77; point2 = new int; *point2 = 173; cout The values are index *point1 *point2 n; delete point2; point1 = new int; point2 = point1; *point1 = 999; cout The values are index *point1 *point2

43、month = 10; date_point-day = 18; date_point-year = 1938; cout month / day / year n; delete date_point; /釋放結(jié)構(gòu)體第57頁/共94頁58 char *c_point; c_point = new char37; /動態(tài)分配數(shù)組 delete c_point; /釋放數(shù)組 c_point = new charsizeof(date) + 133; /動態(tài)分配數(shù)組 delete c_point; /釋放數(shù)組 return 0;運行結(jié)果:The values are 77 77 173The va

44、lues are 77 999 99910/18/1938第58頁/共94頁59對象的動態(tài)建立和釋放對象的動態(tài)建立和釋放如果已經(jīng)定義了一個box類,可以用下面的方法動態(tài)的建立一個對象:new box;定義一個指向本類的對象的指針變量來存放地址box *pt;pt=new box;第59頁/共94頁60在程序中就可以通過pt訪問這個新建的對象,coutheighr;coutvolume();c+還允許在執(zhí)行new時,對新建的對象進行初始化??梢允褂胐elete運算符對新建的對象所占有的空間進行套釋放。delete pt;在執(zhí)行運算符時,自動調(diào)用析構(gòu)函數(shù)。第60頁/共94頁61例例 動態(tài)創(chuàng)建對象舉

45、例動態(tài)創(chuàng)建對象舉例#includeclass Point public: Point( ) X=Y=0; coutDefault Constructor called.n; Point(int xx,int yy) X=xx; Y=yy; cout Constructor called.n; Point( ) coutDestructor called.n; int GetX( ) return X; int GetY( ) return Y;void Move(int x,int y) X=x; Y=y; private: int X,Y;第61頁/共94頁62void main( ) co

46、utStep One:endl; Point *Ptr1=new Point; delete Ptr1; coutStep Two:endl; Ptr1=new Point(1,2); delete Ptr1;運行結(jié)果:運行結(jié)果:Step One:Default Constructor called.Destructor called.Step Two:Constructor called.Destructor called.第62頁/共94頁63例例 動態(tài)創(chuàng)建對象數(shù)組舉例動態(tài)創(chuàng)建對象數(shù)組舉例#includeclass Point /類的聲明同例6-15,略;void main( ) Poin

47、t *Ptr=new Point2; /創(chuàng)建對象數(shù)組 Ptr0.Move(5,10); /通過指針訪問數(shù)組元素的成員 Ptr1.Move(15,20); /通過指針訪問數(shù)組元素的成員 coutDeleting.endl; delete Ptr; /刪除整個對象數(shù)組運行結(jié)果:運行結(jié)果:Default Constructor called.Default Constructor called.Deleting.Destructor called.Destructor called.第63頁/共94頁64訪問對象的數(shù)據(jù)成員訪問對象的數(shù)據(jù)成員#include using namespace std;c

48、lass Humanpublic:int get()constreturn i;void set(int x)i=x;private:int i;int main()Human *p=new Human;p-set(1);coutget()endl;delete p;return 0;運行結(jié)果:運行結(jié)果:1第64頁/共94頁65在構(gòu)造函數(shù)中開辟空間在構(gòu)造函數(shù)中開辟空間#include using namespace std;class Humanpublic:int get()constreturn *i;void set(int x)*i=x;Human();Human();private:

49、int *i;Human:Human()cout構(gòu)造函數(shù)執(zhí)行中.n;i=new int(999);int main()Human *p=new Human;coutget()set(1);coutget()endl;delete p;return 0;Human:Human()cout析構(gòu)函數(shù)執(zhí)行中.n;delete i;構(gòu)造函數(shù)執(zhí)行中9991析構(gòu)函數(shù)執(zhí)行中第65頁/共94頁669.10.1 Allocating memory dynamically for an array The new memory allocation operator can be used to allocate

50、a contiguous block of memory for an array of any type, whether the data type is built-in or is a user-defined structure of class. pointer = new data_typesize ; For example: / Allocate memory for 10 integers. int_ptr = new int10; / Allocate memory for 5 bank_account objects. ac_ptr = new bank_account

51、5;When allocating memory for an array of class objects, there must be a default constructor for the class so that the elements of the array get initialised.(當(dāng)為一個類對象數(shù)組動態(tài)分配內(nèi)存時,這個類必須有自己的默認構(gòu)造函數(shù)來初始化類對象數(shù)組元素。)第66頁/共94頁67/dynamic memory allocation for an array of integers.#includeusing namespace std;main()

52、int* int_array; int no_els, i; cout no_els; int_array = new intno_els; for ( i = 0 ; i no_els ; i+) cout “Enter element ”i int_arrayi; for( i = 0;i no_els;i+) cout“Element”i“ is “*(int_array+i)endl; delete int_array;Enter the number of elements 2Enter element 0: 57Enter element 1: 69Element 0 is 57E

53、lement 1 is 69第67頁/共94頁68 The elements of the newly allocated array can be accessed using either a pointer or an index.(可以使用指針或下標(biāo)方式訪問新分配內(nèi)存的數(shù)組元素。) int_array1*(int_array+1) The allocated memory is freed using the delete operator. It is important to remember to include the square brackets when freeing

54、memory for a previously allocated array. Without the square brackets, only the first element of the array will be deleted.(可以使用delete運算符釋放已分配的內(nèi)存。當(dāng)為一個數(shù)組釋放先前動態(tài)分配的內(nèi)存時,必須用方括號。如果不加釋放的僅是數(shù)組的第一個元素的內(nèi)存。)第68頁/共94頁699.10.2 Initialisation with newuWhen allocating memory for an array of class objects, the default

55、 constructor for the class initialises the elements of the array.(當(dāng)為一個類對象的數(shù)組動態(tài)分配內(nèi)存時,會自動調(diào)用類的默認構(gòu)造函數(shù)對數(shù)組元素進行初始化。) Ac_ptr = new bank_account5;results in the default constructor for the bank account class being called five times.uNo initialisation is done for dynamically allocated arrays of built-in data

56、types. (對內(nèi)置數(shù)據(jù)類型的數(shù)組動態(tài)分配內(nèi)存時無需對其初始化。)For example, int_ptr = new int10;results in the ten non-initialised integer elements.第69頁/共94頁70uSingle instances of any data type(built-in, a user-defined structure or a class) can be initialised using a second form of the new operator.(對任意數(shù)據(jù)類型的單個實例,可以使用new運算符的另一種形

57、式對其進行初始化。) pointer = new data_type( initial_value);Eg. /allocate memory for an integer, with an initial value of 100. int_ptr = new int(100); /allocate memory for an integer, with no initial value. int_ptr = new int; /allocate memory for a bank_account object. The default constructor is /called to d

58、o the initialisation. ac_ptr = new bank_account; /allocate memory for a bank_account object. A constructor is called to /assign initial values to account number and balance. ac_ptr = new bank_account(1234,100);初始值是可選的第70頁/共94頁71#include#include#include “bank_ac.h”#include “bank_ac.cpp”using namespac

59、e std;main() int no_of_acs; cout no_of_acs; bank_account* accounts = new bank_accountno_of_acs; cout endl “Accounts:” endl; for(int i = 0;i no_of_acs;i+) accountsi.display_balance(); cout endl;第71頁/共94頁72cout“bank_ptr1:”display_balance();coutendl;bank_account* bank_ptr2=new bank_account(123,100);cou

60、t“bank_ptr2:”display_balance();delete accounts;delete bank_ptr1;delete bank_ptr2; 運行結(jié)果運行結(jié)果Enter the number of bank accounts 2Account:bank_ptr1:bank_prt2:第72頁/共94頁739.10.3 allocating memory for multi-dimensional arrays In C+, multi-dimensional arrays are implemented as arrays of arrays. To fully understand dynamic memory allocation for multi-dimensional arrays, familiarity with section 9.6 is necessary.第73頁/共94頁74#include#includeusing namespace std;main() int

溫馨提示

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

評論

0/150

提交評論