C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS

上传人:cl****1 文档编号:569595299 上传时间:2024-07-30 格式:PPT 页数:127 大小:482KB
返回 下载 相关 举报
C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS_第1页
第1页 / 共127页
C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS_第2页
第2页 / 共127页
C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS_第3页
第3页 / 共127页
C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS_第4页
第4页 / 共127页
C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS_第5页
第5页 / 共127页
点击查看更多>>
资源描述

《C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS》由会员分享,可在线阅读,更多相关《C++程序设计教学课件:CHAPTER 7 ARRAYS AND POINTERS(127页珍藏版)》请在金锄头文库上搜索。

1、C+ Programming CHAPTER 7 ARRAYS AND POINTERS1l7.1 Arraysl7.2 Pointersl7.3 The new and delete Operators l7.4 String27.1 ArraysArraysArraysArrays are a kind of composite type because they allow you to clump a lot of variables together, one right after the other, under a single identifier name.37.1 Arr

2、aysArraysSyntax:type ArrayName constant expression ;Example:int a10;You create storage for 10 int variables stacked on top of each other. They are all lumped under the name a. 47.1 ArraysArraysTo access one of these array elements, you use the same square-bracket syntax that you use to define an arr

3、ay:a5 = 47;57.1 ArraysArraysHowever, you must remember that even though the size of a is 10, you select array elements starting at zero ,so you can select only the array elements 0-9.67.1 ArraysArrays#include using namespace std;int main() int a10; for(int i = 0; i 10; i+) ai = i * 10; cout a i = ai

4、 endl; 77.1 ArraysArraysRemarks:A) The memory address location of the elements in the array is consecutive.B) The name of the array is the memory address location of the first element in the array.C) The name of the array is a constant.87.1 ArraysArraysa0 a1 a2 a3 a4 a5 a6 a7 a8 a9a:97.1 ArraysArray

5、sInitializationThere are many ways of initializing the arrays.1) static int a10=0,1,2,3,4,5,6,7,8,9;2) static int a10=0,1,2,3,4;3) static int a=1,2,3,4,5107.1 ArraysArraysTwo Dimensional ArraysSyntax:type ArrayName constant expression constant expression ;Example:int a105;You create storage for 50,

6、10*5, int variables in an array.117.1 ArraysArraysInitialization:1) static int a34=1,2,3,4,5,6,7,8,9,10,11,12;2) static int a34=1,2,3,4,5,6,7,8,9,10,11,12;3) static int a34=1,0,6,0,0,11; 127.1 ArraysArraysArray ArgumentThe fact that naming an array produces its starting address turns out to be quite

7、 important when you want to pass an array to a function. 137.1 ArraysArraysIf you declare an array as a function argument, what youre really declaring is a pointer. Arrays cant be passed by value, that is, you never automatically get a local copy of the array that you pass into a function. When you

8、modify an array, youre always modifying the outside object.147.1 ArraysArraysExample:#include #include using namespace std;void func1(int a, int size) for(int i = 0; i size; i+) ai = i * i - i;void print(int a, string name, int size) for(int i = 0; i size; i+) cout name i = ai endl;157.1 ArraysArray

9、sint main() int a5; / Probably garbage values: print(a, a, 5); / Initialize the arrays: func1(a, 5); print(a, a, 5); return 0; Output:a0 = -858993460a1 = -858993460a2 = -858993460a3 = -858993460a4 = -858993460a0 = 0a1 = 1a2 = 2a3 = 3a4 = 4167.1 ArraysObject ArraysDefine ArraysSyntax:ClassName ArrayN

10、ame constant expression ;Example:Time t10;t0.SetTime(1900,1,1);You create storage for 10 Time variables in an array.177.1 ArraysObject ArraysInitialization1) Time t2=Time(1900,1,1), Time(1900,2,2);2) Time t2;187.1 ArraysObject ArraysRemarks:A) Every element in the array calls the constructor automat

11、ically.B) If there is not a user defined constructor, the C+ system will provide a default constructor.C) The constructor can be default argument function, too.D) Every element calls the destructor when it is delete.19Example:/Point.h#if !defined(_POINT_H)#define _POINT_Hclass Point public: Point();

12、 Point(int xx,int yy); Point(); void Move(int x,int y); int GetX() return X; int GetY() return Y;private: int X,Y;#endif20/Point.cpp#includeusing namespace std;#include Point.hPoint:Point() X=Y=0; coutDefault Constructor called.endl;Point:Point(int xx,int yy) X=xx; Y=yy; cout Constructor called.endl

13、;Point :Point() coutDestructor called.endl; void Point :Move(int x,int y) X=x; Y=y; 21#include#include Point.husing namespace std;int main() coutEntering main.endl; Point A2; for(int i=0;i2;i+) Ai.Move(i+10,i+20); coutExiting main.endl; return 0; Output:Entering main.Default Constructor called.Defau

14、lt Constructor called.Exiting main.Destructor called.Destructor called.227.2 Pointers IntroductionSince your program lives in memory while its being run, every element of your program has an address. 237.2 Pointers IntroductionThere is an operator in C and C+ that will tell you the address of an ele

15、ment. This is the & operator. All you do is precede the identifier name with & and it will produce the address of that identifier. So pointer is the address of the element in a program.247.2 Pointers IntroductionDefine PointersExample:int i; int *i_pointer=&i; i=3; *i_pointer=3;memoryvariable ivaria

16、ble jvariable i_pointer36200020002004301020003i_pointer*i_pointeri2000257.2 Pointers IntroductionInitializationSyntax:Storage Allocation type *PointerNameaddress;Example:int *pa=&a;267.2 Pointers IntroductionRemarks:A) If a pointer is initialized by an address of a variable, the variable must be def

17、ined before initialized, and the type must match, too.B) A pointer can be initialized by another pointer, which is initialized already.C) Dont initialize a static pointer by an auto pointer.277.2 Pointers IntroductionD) The type of a pointer means the type of the variable that the pointer points to.

18、 The type of the pointer itself is unsigned long int. E) Only void pointer can point to any type of data.Example:void *general;287.2 Pointers IntroductionExample:#includeusing namespace std;void main() int *i_pointer; int i;i_pointer=&i;i=10;coutOutput int i=iendl; coutOutput int pointer i=*i_pointe

19、rendl;Output:Output int i=10Output int pointer i=10297.2 Pointers IntroductionExample:int iCount=26;int* iPtr;*iPtr=56; *iPtr=&iCount; /wrong/wrong307.2 Pointers Pointers and ConstantsPointers and ConstantsPointers can be made const. When using const with pointers, you have two options: const can be

20、 applied to what the pointer is pointing to, or the const can be applied to the address stored in the pointer itself.317.2 Pointers Pointers and ConstantsPointer to Constif you want to prevent any changes to the element you are pointing to, you write a definition like this:const int* u;Remark:Only t

21、he pointer pointing to is const, the pointer itself is not const. 327.2 Pointers Pointers and ConstantsExample:char *name1 = John; /name1 is a pointer*name1=A; /it is right after compiled, but results /wrong when it runsExample:const char *name1 = John; /name1 points to a const s=abc;name1=s; *name1

22、=1; /right/wrong337.2 Pointers Pointers and ConstantsExample: const int a = 78; const int b=28; int c=18; const int *pi = &a; *pi = 85; pi = &b; *pi = 90; pi = &c; *pi = 88; c = 98;347.2 Pointers Pointers and ConstantsGiven the definition “const int * pi=&a;” means *pi is const.Question: A pointer c

23、an not point to a const if the pointer is not a pointer to const, why?357.2 Pointers Pointers and ConstantsConst PointerTo make the pointer itself a const, you must place the const specifier to the right of the *, like this:int d = 1;int* const w = &d;Remark:Only the pointer itself is const, the poi

24、nter pointing to is not const.367.2 Pointers Pointers and ConstantsExample:char *const name2 = John; name2=abc; /wrong, the pointer itself is const377.2 Pointers Pointers and ConstantsExample:char* const pc=“asdf”; pc=“dfgh”; const int b=30;int* const pi=&b;Given the definition“ int * const pi=&b;”

25、means pi is const, but *pi is not const. 387.2 Pointers Pointers and ConstantsConst Pointer to ConstYou can also make a const pointer to a const object using either of two legal forms:int d = 1;const int* const x = &d; int const* const x2 = &d; Now neither the pointer nor the object can be changed.3

26、97.2 Pointers Pointers and ConstantsExample:const int ci=7;int ai;const int * const cpc=&ci; const int* const cpi=&ai; cpi=&ai; *cpi=39; ai=39;Given the definition “cont int * const cpc=&b; ” means both cpc and *cpc are const. 407.2 Pointers Pointers and ArraysAddition and Subtraction of PointersIf

27、p is a pointer, then p+n means the pointer p points to the address of the next n variable. In the 32bit machine:1 addition to a char type pointer means 1;1 addition to a long type pointer means 4;1 addition to a float type pointer means 4;1 addition to a double type pointer means 8;417.2 Pointers Po

28、inters and Arrayspapa-2pa-1pa+1pa+2pa+3*(pa-2)*pa*(pa+1)*(pa+2)*(pa+3)*(pa-1)short *pa427.2 Pointers Pointers and Arrayspb-1pbpb+1pb+2*(pb-1)*pb*(pb+1)*(pb+2)long *pb437.2 Pointers Pointers and ArraysPointer to ArraysExample:int a10, *pa;pa=&a0; /or pa=a;*pa means a0, *(pa+1) means a1, . , *(pa+i) m

29、eans ai. ai, *(pa+i), *(a+i), pai are equal.Remark:a+ is illegal, because a is the address of the array, and it is const.447.2 Pointers Pointers and ArraysArray PointersExample:Point *pa2;pa0 and pa1 are both pointer that pointing to Point.457.2 Pointers Pointers and ArraysExample:#include using nam

30、espace std;void main() int line1=1,0,0; /first line of the matrixint line2=0,1,0; /second line of the matrixint line3=0,0,1; /third line of the matrixint *p_line3;/array pointersp_line0=line1;/initializationp_line1=line2;p_line2=line3;467.2 Pointers Pointers and Arrays/output the matrix coutMatrix t

31、est:endl;for(int i=0;i3;i+)/ for every pointerfor(int j=0;j3;j+)/ for every line of the matrix coutp_lineij ; coutendl;Output:Matrix test:1,0,00,1,00,0,1 477.2 Pointers Pointers in FunctionsPointer ArgumentsPassing data by pointer will result the change of the arguments.487.2 Pointers Pointers in Fu

32、nctionsExample:#include #include using namespace std;void Array_Ptr(long *P, int n)int i;cout In func, address of array is unsigned long(P) endl;cout Accessing array in the function using pointers endl;497.2 Pointers Pointers in Functionsfor (i = 0; i n; i+)cout Address for index i is unsigned long(

33、P+i);cout Value is *(P+i) endl;507.2 Pointers Pointers in Functionsvoid main(void)long list5 = 50, 60, 70, 80, 90;cout In main, address of array is unsigned long(list) endl;cout endl;Array_Ptr(list,5);517.2 Pointers Pointers in FunctionsOutput:In main, address of array is 6684132In func, address of

34、array is 6684132Accessing array in the function using pointersAddress for index 0 is 6684132 Value is 50Address for index 1 is 6684136 Value is 60Address for index 2 is 6684140 Value is 70Address for index 3 is 6684144 Value is 80Address for index 4 is 6684148 Value is 90527.2 Pointers Pointers in F

35、unctionsIf you dont want the argument to be changed, you can use the pointers pointing to const as the arguments.537.2 Pointers Pointers in FunctionsExample:#includeusing namespace std;const int N=6;void print(const int *p,int n);void main() int arrayN; for(int i=0;iarrayi; print(array,N);547.2 Poin

36、ters Pointers in Functionsvoid print(const int *p, int n) cout*p; for(int i=1;in;i+) cout.*(p+i); coutendl;557.2 Pointers Pointers in FunctionsPointer FunctionsYou can define a function that return a value of pointer.Example:static point* getP();567.2 Pointers Pointers in FunctionsPointer to Functio

37、nsA pointer can not only point to the variable in a program, but also points to a function in a program.577.2 Pointers Pointers in Functions#include using namespace std;void print_stuff(float data_to_ignore);void print_message(float list_this_data);void print_float(float data_to_print);void (*functi

38、on_pointer)(float);void main()float pi = (float)3.14159;float two_pi = (float)2.0 * pi;58 print_stuff(pi); function_pointer = print_stuff; function_pointer(pi); function_pointer = print_message; function_pointer(two_pi); function_pointer(13.0); function_pointer = print_float; function_pointer(pi); p

39、rint_float(pi);597.2 Pointers Pointers in Functions59void print_stuff(float data_to_ignore) coutThis is the print stuff function.n; void print_message(float list_this_data) coutThe data to be listed is list_this_dataendl; void print_float(float data_to_print) coutThe data to be printed is data_to_pr

40、intgetx(); / or (*ptr).getx();627.2 Pointers Pointers in ClassesExample:int main()Point A(5,10);Point *ptr;ptr=&A;int x;x=ptr-GetX();coutx* DataMemberPointer;667.2 Pointers Pointers in ClassesExample:class Apublic:int a;int b;void main()A obj; int A:*p;p=&A:a;obj.*p = 9;/obj.a=9;p=&A:b;obj.*p = 10;/

41、obj.b=10677.2 Pointers Pointers in Classes2 Pointers to Public Methods:Syntax:type (ClassName:*MethodPointer)(ArgumentList);Initialization:MethodPointer = ClassName:MethodName;687.2 Pointers Pointers in ClassesMember Access:(Object.* MethodPointer)(ArgumentList)or:(ObjectPointer* MethodPointer)(Argu

42、mentList)69Example:void main()Point A(4,5); /object APoint *p1=&A;/pointer to object /define a pointer to public method and initializedint (Point:*p_GetX)()=Point:GetX; /using method pointer to access methodcout(A.*p_GetX)()endl; /using object pointer to access methodcoutGetX)()endl; /using object t

43、o access methodcoutA.GetX()endl; 707.2 Pointers Pointers in ClassesPointers to Static MembersStatic members can be accessed by using class name and scope resolution. We can define and access the static members of class by usual pointers.71Example: Pointers to Static Data Members#include using namesp

44、ace std;class Pointpublic:Point(int xx=0, int yy=0) X=xx;Y=yy;countP+;/constructorPoint(Point &p);/copy constructorint GetX() return X;int GetY() return Y;static int countP;/static data memberprivate:int X,Y;Point:Point(Point &p)X=p.X; Y=p.Y; countP+; 72int Point:countP=0;/ Initialization of the sta

45、tic data membervoid main() /pointer to the static data membersint *count=&Point:countP; Point A(4,5);coutPoint A,A.GetX(),A.GetY(); /access the static data members by pointercout Object id=*countendl;Point B(A);coutPoint B,B.GetX(),B.GetY(); /access the static data members by pointercout Object id=*

46、countendl; 73Example: Pointers to Static Methods#include using namespace std;class Pointpublic:/static void GetC() /static method cout Object id=countPendl;private:int X,Y;static int countP; /static data member;/ 74int Point:countP=0;/ Initialization void main() /pointer to static methodvoid (*gc)()

47、=Point:GetC;Point A(4,5);coutPoint A,A.GetX(),A.GetY(); /access static method by pointergc(); Point B(A);coutPoint B,B.GetX(),B.GetY(); /access static method by pointergc(); Output:757.3 The new and delete Operators New and DeleteNew and DeleteThe new, new , delete, and delete operators are used to

48、allocate and free storage dynamically. The operator new allocates a single cell; new allocates an array; delete frees a single cell allocated by new; and delete frees an array allocated by new . 767.3 The new and delete Operators New and DeleteNew, new , delete, and delete are built-in operators whi

49、le malloc and free are C library functions.When you create an object with new, it allocates enough storage on the heap to hold the object and calls the constructor for that storage.777.3 The new and delete Operators New and DeleteSyntax:new type(ArgumentList);delete pointer;787.3 The new and delete

50、Operators New and DeleteExample:#includeusing namespace std;class 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; pri

51、vate: int X,Y;797.3 The new and delete Operators New and Deleteint main() coutStep One:endl;Point *Ptr1=new Point;delete Ptr1; coutStep Two:endl;Ptr1=new Point(1,2);delete Ptr1;return 0;Output:Step One:Default Constructor called.Destructor called.Step Two:Constructor called.Destructor called.Questio

52、n: When was Ptr1 deleted?80Example:#includeusing namespace std;class Point / ;class ArrayOfPoints public: ArrayOfPoints(int n) numberOfPoints=n; points=new Pointn; ArrayOfPoints() coutDeleting.endl; numberOfPoints=0; delete points; Point& Element(int n) return pointsn; private: Point *points; int nu

53、mberOfPoints;81void main() int number; coutnumber; /object array ArrayOfPoints points(number); points.Element(0).Move(5,10); points.Element(1).Move(15,20); Output:Please enter the number of points:2Default Constructor called.Default Constructor called.Deleting.Destructor called.Destructor called.Que

54、stion: What is the difference between delete p and delete p?827.3 The new and delete Operators Multidimensional ArrayMultidimensional ArraySyntax:new typesubscripting1 subscripting2;Example:char (*fp)3;fp = new char23;83char (*fp)3;fpfp+1fp00fp01fp02fp10fp11fp1284Example:#includeusing namespace std;

55、void main()float (*cp)98;int i,j,k;cp = new float898;for (i=0; i8; i+)for (j=0; j9; j+)for (k=0; k8; k+) *(*(*(cp+i)+j)+k)=i*100+j*10+k; 85 /access elements of array by pointerfor (i=0; i8; i+)for (j=0; j9; j+) for (k=0; k8; k+) /pointer cp means the name of the array coutcpijk ; coutendl;coutendl;

56、867.3 The new and delete Operators Copy ConstructorsWhen copy constructors are invoked, if there is a pointer member in the class, we can use the bitcopy to copy the pointer, or define our own copy constructor to copy the resource that the pointer pointing to.877.3 The new and delete Operators Copy

57、ConstructorsExample:#includeusing namespace std;class Point / /;class ArrayOfPoints / /;88void main()int number;cinnumber; ArrayOfPoints pointsArray1(number); pointsArray1.Element(0).Move(5,10); pointsArray1.Element(1).Move(15,20); ArrayOfPoints pointsArray2(pointsArray1); coutCopy of pointsArray1:e

58、ndl; coutPoint_0 of array2: pointsArray2.Element(0).GetX() , pointsArray2.Element(0).GetY()endl; coutPoint_1 of array2: pointsArray2.Element(1).GetX() , pointsArray2.Element(1).GetY()endl;89 pointsArray1.Element(0).Move(25,30); pointsArray1.Element(1).Move(35,40); coutAfter the moving of pointsArray

59、1:endl; coutPoint_0 of array2: pointsArray2.Element(0).GetX() , pointsArray2.Element(0).GetY()endl; coutPoint_1 of array2: pointsArray2.Element(1).GetX(), pointsArray2.Element(1).GetY()endl;90Output:Please enter the number of points:2Default Constructor called.Default Constructor called.Copy of poin

60、tsArray1:Point_0 of array2: 5, 10Point_1 of array2: 15, 20After the moving of pointsArray1:Point_0 of array2: 25, 30Point_1 of array2: 35, 40Deleting.Destructor called.Destructor called.Deleting.It results a run time error, why?91pointsArray1pointsnumberOfPointsnumberOfPointspointsArray1before copy

61、constructor is invoked:pointsnumberOfPointsnumberOfPointspointsArray2pointsnumberOfPointsnumberOfPointspointsArray1pointsArray1after copy constructor is invoked:927.3 The new and delete Operators Copy ConstructorsExample:Solution#includeusing namespace std;class Point / ;class ArrayOfPoints public:

62、ArrayOfPoints(ArrayOfPoints& pointsArray); / ;937.3 The new and delete Operators Copy ConstructorsArrayOfPoints :ArrayOfPoints(ArrayOfPoints&pointsArray) numberOfPoints =pointsArray.numberOfPoints; points=new PointnumberOfPoints; for (int i=0; inumberOfPoints; i+) pointsi.Move(pointsArray.Element(i)

63、.GetX(), pointsArray.Element(i).GetY();void main() / 947.3 The new and delete Operators Copy ConstructorsOutput:Please enter the number of points:2Default Constructor called.Default Constructor called.Default Constructor called.Default Constructor called.Copy of pointsArray1:Point_0 of array2: 5, 10

64、Point_1 of array2: 15, 20957.3 The new and delete Operators Copy ConstructorsAfter the moving of pointsArray1:Point_0 of array2: 5, 10Point_1 of array2: 15, 20Deleting.Destructor called.Destructor called.Deleting.Destructor called.Destructor called.96before copy constructor is invoked:pointsArray1po

65、intsnumberOfPointsnumberOfPointspointsArray1after copy constructor is invoked:pointsnumberOfPointsnumberOfPointspointsArray1pointsArray1pointsnumberOfPointsnumberOfPointspointsArray2977.4 StringsArrays of CharIn C+ arrays of char are useful because there is not a built-in data type to store a string

66、.Remark:A string stored by array of char ends by 0.987.4 StringsArrays of CharExample:static char str8=112,114,111,103,114,97,109,0;static char str8=p,r,o,g,r,a,m,0;static char str8=program;static char str=program;997.4 StringsArrays of CharExample:#includeusing namespace std;void main() static char

67、 c10=I, ,a,m, ,a, ,b,o,y; int i; for(i=0;i10;i+)coutci; coutendl;Output:I am a boy1007.4 StringsArrays of CharInput and OutputWe can input or output a string by array of char at once.Example:char c=China;char a10;couta;1017.4 StringsArrays of CharRemarks:A) The characters output by array dont includ

68、e 0.B) Space is not included in an array of char.1027.4 StringsArrays of CharExample:static char str15,str25,str35;cinstr1str2str3;Input:How are you?Memory:str1: How0 str2: are0 str3: you?01037.4 StringsArrays of CharExample:static char str13;cinstr;Input:How are you?Memory:str1: How0 1047.4 Strings

69、Arrays of CharExample:char a4, *p1, *p2;a=abc; cinp1;p1=abc;p2=a;cinp2;/ compile error/run time error1057.4 StringsArrays of Chargetline and getcin.getline ( char* pch, int nCount, char delim = n );Parameters:pch:A pointer to a character array.nCount:The maximum number of characters to store, includ

70、ing the terminating NULL.delim:The delimiter character (defaults to newline).1067.4 StringsArrays of CharRemarks:Extracts characters from the stream until either the delimiter delim is found, the limit nCount1 is reached, or end of file is reached. The characters are stored in the specified array fo

71、llowed by a null terminator. If the delimiter is found, it is extracted but not stored.1077.4 StringsArrays of Charcin.get(char* pch, int nCount, char delim = n);Parameters:pch:A pointer to a character array.nCount:The maximum number of characters to store, including the terminating NULL.delim:The d

72、elimiter character (defaults to newline).1087.4 StringsArrays of CharRemark:Extracts characters from the stream until either delim is found, the limit nCount is reached, or the end of file is reached. The characters are stored in the array followed by a null terminator.1097.4 StringsArrays of CharEx

73、ample:#include using namespace std;void main (void)char city80;char state80;int i;for (i = 0; i 2; i+) cin.getline(city,80,); cin.getline(state,80,n); cout City: city State: state endl;1107.4 StringsArrays of CharResults:Input:Beijing,ChinaOutput:City: Beijing Country: China Input:Shanghai,ChinaOutp

74、ut:City: Shanghai Country: China1117.4 StringsArrays of CharFunctionschar *strcat( char *strDestination, const char *strSource ); char *strcpy( char *strDestination, const char *strSource ); int strcmp( const char *string1, const char *string2 );char *strlen( const char *string );char *_strlwr( char

75、 *string ); char *_strupr( char *string );1127.4 StringsStringsDefinitionC+ furnishes the type string as an alternative to Cs null-terminated arrays of char. Use of type string requires the header string.1137.4 StringsStringsExample:#include using namespace std;string s1;string s2=”Bravo”;string s3=

76、s2;string s4(10,x);1147.4 StringsStringsInput and OutputOperator and string s;cins;Input:Ed WoodResult:string s: Ed1167.4 StringsStringsExample:string s1;string s2=”Bravo”;string s3=s2;string s4(10,x);couts1n s2n s3n s4n;Output:BravoBravoxxxxxxxxxx1177.4 StringsStringsAssignment and ConcatenationThe

77、 assignment operator = can be used to perform string assignments.1187.4 StringsStringsExample:string s1,s2;s1=”Ray Dennis Steckler”;s2=s1;couts1endl;couts2endl;Output:Ray Dennis StecklerRay Dennis Steckler1197.4 StringsStringsOperators + and += can be used to perform string concatenation.Example:str

78、ing s1=”Atlas”;string s2=”King”;string s3;s3=s1+s2;couts3endl;s1+=s2;couts1;Output:Atlas KingAtlas King1207.4 StringsStringsExtracting a SubstringExample:string s1=”Ray Dennis Stechler”;string s2;s2=s1.substr(4,6);cout=ind where s2 begins.1227.4 StringsStringsExample:string s1=”Ray Dennis Stechler”;

79、string s2=” Dennis”; int f; f=s1.find(s2); if(fs1.length() cout”Found at index:”fendl;else cout”Not found”endl;Output:Found at index:41237.4 StringsStringsComparing StringsThe operators =, !=, , and = can be used for string comparison.124Example:#include #include using namespace std ;void trueFalse(

80、int x) cout (x? True: False) endl;125void main() string S1=DEF, S2=123; char CP1 =ABC; char CP2 =DEF; cout S1 is S1 endl; cout S2 is S2 endl; coutlength of S2:“ S2.length()endl; cout CP1 is CP1 endl; cout CP2 is CP2 endl; cout S1=CP1 returned ; trueFalse(S1=CP1); cout CP2=S1 returned ; trueFalse(CP2=S1); S2+=S1; coutS2=S2+S1:S2endl; coutlength of S2:S2.length()endl;Output:S1 is DEFS2 is 123length of S2:3CP1 is ABCCP2 is DEFS1=CP1 returned FalseCP2=S1 returned TrueS2=S2+S1:123DEFlength of S2:6126SummarizeArraysPointersThe new and delete Operators String127

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 研究生课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号