CC++:从基础语法到优化策略 (4).pdf

上传人:奉*** 文档编号:67731787 上传时间:2022-12-26 格式:PDF 页数:28 大小:8.78MB
返回 下载 相关 举报
CC++:从基础语法到优化策略 (4).pdf_第1页
第1页 / 共28页
CC++:从基础语法到优化策略 (4).pdf_第2页
第2页 / 共28页
点击查看更多>>
资源描述

《CC++:从基础语法到优化策略 (4).pdf》由会员分享,可在线阅读,更多相关《CC++:从基础语法到优化策略 (4).pdf(28页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、C/C+Program DesignCS205Week 4Content Arrays Array-style strings string-class strings Structures Unions EnumerationsArrayThe slides are based on the book Data TypesFundamental types Integer Typeboolshort,int,long Char Type:char Floating-point Type:float,doubleCompound typesArrayArray-style string Str

2、ing classStructureArrays An array is a data form that can hold several values,all of one typeone type To define:The type of value to be stored in each elementThe name of the arrayThe number of elements in the array must be an integer constant,such as 10 or a const value,MICROS,or a constant expressi

3、onSquare brackets Why?Arrays Some statements for an arrayDeclaring an arrayAssigning values to array elementsInitializing an array Run program example/arrayone.cpp-small arrays of integersNote that if you use the sizeof operator with an array name,you get the number of bytes in the whole arrayFirst

4、element index is 0Error:if subscript is equal or greater than the number of elements Initialization Rules for Arrays Several rules about initializing arrays Able to Use the initialization form only when defining the array Use subscripts and assign values to the elements of an array individually Part

5、ially initialize an array,the compiler sets the remaining elements to zeroCannot Use initialization later Assign one array wholesale to anotherC+11 Array Initialization Rules in C+11Can drop the=signCannot convert from a floating-point type to an integer type(narrowing)Cannot assign int type to char

6、 type(Outside the range of a char)StringThe slides are based on the book Strings A string is a series of characters stored in consecutivebytes of memoryC-style(array)stringstring class library Store a stringin an array of char(C-style)The last character of every string is the null characterThis null

7、 character is written 0The character is with ASCII code 0It serves to mark the strings endStrings Using a double quoted stringCalled a string constant or string literalInclude the terminating null character implicitlyMake sure the array is large enough to hold all the charactersNote that a string co

8、nstant(with double quotes”)is not interchangeable with a character constant(with single quotes )Example cstrinit.cppConcatenating String Literals C+enables to concatenate string literalsAny two string constants separated only by whitespace Run program exampleUsing Strings in an Array/strings.cpp-sto

9、ring strings in an array Shortening a string with 0 Beware of memory overflow(Problem)Adventures in String Input Run program example/instr1.cpp-reading more than one stringThe cin technique is to use whitespacespaces,tabs,and newlines(0)to delineate a stringThe input string might turn out to be long

10、er than the destination array(buffer)A white space causes a problemReading String Input a Line at a Time(solved)To solve the problem:Line-oriented input with getline()See program example/instr2.cpp-reading more than one word with getline()Two argumentsOther Forms of String Literals Beside char,we ha

11、ve more following typeswchar_tchar16_tchar32_tchar8_t /c+2a char8_t name=u8SUSTech”;/UINT8 example wstr.cppstring-class stringsThe slides are based on the book string class The ISO/ANSI C+98 Standard expanded the C+library Include the string header file:#include Run program example strtype1.cppIniti

12、alize a string object,in a similar way as a C-style stringUse cin to store keyboard input in a string objectUse cout to display a string objectUse array notation to access individual characters stored in a string object DifferencesTreat object as a simple variable,not as an arrayAllow the program to

13、 handle the sizing automaticallyC+11 String Initialization C+11 enables 4 kinds of initialization Array-style String class Assign one string object to another Array assignment Use the+and+=operatorsMore string Class Operations Three functions for array-style stringstrcpy():copy a string to a charact

14、er array =strcat():append a string to a character array +=strlen():calculate the length of a character array *.size()See three operations in program example strtype3.cpp Conclusionsstring objects tends to be simplersimplerthan using the C string functionsstring objects tends to be more safesafethan

15、that of the CMore on string Class I/O See length of string in program example strtype4.cpp The difference and problems of array-style stringstrlen()reaches a null characterstring object is automatically set to zero sizeArray-style string has fixed size of inputcin.getline(charr,20);/Array-style stri

16、ng getline(cin,str);/string classStructures,Unions and EnumerationsThe slides are based on the book Introducing Structures Why structures?Almost all previous types are those you can directly useA structure is a more versatile data form than an arrayA structure is a user-definable type The keyword st

17、ruct make a new typeUsing a Structure in a Program How to create a structure?Where to place the structure declaration?Inside or outside of mainCan a structure use a string class member?YesAssignment:use a comma-separated list of values enclosed in a pair of bracesIn C+11,the=sign is optionalEmpty br

18、aces result in the individual members being set to 0 See assignment and member access in program example stracture.cppOther Structure Properties What actions you can do for structures?Pass structures as arguments(multiple)to a function Have a function use a structure as a return value(multiple)Combi

19、ne the definition of a structure form with the creation of structure variables Have member functions in addition to member variables Run program example assgn_st.cpp Member-wise assignment:use the assignment operator(=)to assign one structure to another of the same typeMore Structure Properties:Arra

20、y Arrays of Structures Create arrays whose elements are structures An examplegifts itself is an array,not a structuregifts0 is a structureUnions A union is a data format Can hold different data types but only one type at a time Can use two or more formats but neversimultaneously Save memory union Ke

21、yword make a new typeprogram example union.cppEnumerations The C+enum facility provides an alternative to const for creating symbolic constants(#define)enum spectrum red,orange,yellow,green,blue,violet;It makes spectrum the name of a new typeIt establishes the members as symbolic constants for the i

22、nteger values 05 By default,enumerators are assigned integer values starting with 0 for the first enumerator,1 for the second enumerator,and so forth The assigned values must be integers enum Keyword make a new typeEnumerations What operations can you do for enumerations?Assign it using the member You can set enumerator values explicitly Assign other variables using it Typecast values within the range Beware of the value ranges for enumerations

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 大学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁