《CC++:从基础语法到优化策略 (1).pdf》由会员分享,可在线阅读,更多相关《CC++:从基础语法到优化策略 (1).pdf(44页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、C/C+Program DesignCS205About meProf.Shiqi Yu(于仕琪于仕琪)Department of Computer Science and Engineering in Southern University of Science and Technology 南方科技大学计算机科学与工程系 Email:http:/ An open source project,OpenCV,is introduced in the course.C+Class cv:Mat is introduced to explain C+knowledges.Dynamic memo
2、ry management and pointer.One of the main advantage of C/C+is its efficiency.How to improve the efficiency of your programs.How to program using an ARM development board.Resources Blackboard:C/C+Program Design Useful websites:http:/cpp.sh/https:/ basic knowledgeThe slides are based on the book High-
3、level Languages High-level languages Similar to English,use common mathematical notations Single statements accomplish substantial tasks:Assembly language requires many instructions to accomplish simple tasks Translator programs(compilers):Convert to machine language Interpreter programs:Directly ex
4、ecute it Example:grossPay=basePay+overTimePay C/C+,JAVA,PYTHON,MATLAB,Programmer =translatorHistory of C Evolved from two other programming languages BCPL and B:“Typeless”languages Dennis Ritchie(Bell Laboratories)Added data typing,other features Development language of UNIX Hardware independent Por
5、table programshttps:/ Combined Programming Language Chttps:/en.wikipedia.org/wiki/C_(programming_language)History of C+Extension of C Early 1980s:Bjarne Stroustrup(Bell Laboratories)Provides capabilities for Object-Oriented ProgrammingObjects:reusable software components:Model items in real worldObj
6、ect-oriented programs:Easy to understand,correct and modify Hybrid languageC-like styleObject-oriented stylehttps:/en.wikipedia.org/wiki/C%2B%2BComparison Procedural versus Object-oriented(Encapsulated:封装的)Class definitionObject declarationProgram Phase Edit Preprocess(how to organize)Compile Link L
7、oad Execute LoaderPrimaryMemoryProgram is created inthe editor and storedon disk.Preprocessor programprocesses the code.Loader puts programin memory.CPU takes eachinstruction andexecutes it,possiblystoring new datavalues as the programexecutes.CompilerCompiler createsobject code and storesit on disk
8、.Linker links the objectcode with the libraries,createsanexecutablefile and stores it on diskEditorPreprocessorLinkerCPUPrimaryMemory.DiskDiskDiskDiskDiskProper Extensions SuffixSoftware Build Process Start with C+source code files(.cpp,.hpp)Compile:convert code to object code stored in object file(
9、.o)Link:combine contents of one or more object files(and possibly some libraries)to produce executable programGNU Compiler Collection(GCC)C+Compiler(编译器)g+command provides both compiling and linking functionality Command-line usage:g+g+options input file.Compile C+source file file.cpp to produce obj
10、ect code file file.o:g+-c file.cpp Link object files file 1.o,file 2.o,.to produce executable file executable_name:g+-o executable_name file 1.o file 2.o.Tools for windows:MinGW,MSYS2,Cygwin,Windows SubsystemCommon g+Command-Line Options Web site:http:/www.gnu.org/software/gcc C+standards support in
11、 GCC:https:/gcc.gnu.org/projects/cxx-status.htmlsamples C,C+and JavaCommand line arguments int main()/*.*/int main(int argc,char*argv).int main(int argc,char*argv).Setting Out to C+The slides are based on the book Content Creating a C+program The#include directive The main()function Placing comments
12、 in a C+program Declaring and using variables Using the cout object for output How and when to use endl Using the cin object for input Defining and using simple functionsC+Program Sample A program exampleNoting:C+is case sensitiveCommentsPreprocessorFunction headerNamespaceFunction bodyStatementsRet
13、urn statementArgument listmyfirst.cppComments(注释)Two styles of comments providedComment starts with/and proceeds to end of lineComment starts with/*and proceeds to first*/The compiler ignores commentsDefinition of the main()Function Function definitionFunction header-a summary of the functions inter
14、faceFunction bodyStatement-each complete instruction+semicolon;Return statementFeatures of the main()Function main()functions are called by startup code-mediate between the program and the operating system Function header-describe the interfacebetween main()and the operating system Standalone progra
15、m-does need a main()Main()or MAIN()or mane()WinMain()or _tmain()OtherwiseA dynamic link library(DLL)A controller chip in a robotC+Preprocessor(预处理)Preprocessor transforms source code,prior to compilationPreprocessor passes the output to compiler for compilationPreprocessor behavior can be controlled
16、 by directivesDirective occupies single line single line of codeNo semicolon(;)Consists of:Can be used to:Preprocessor:Source-File Inclusion Include contents of another file in source using preprocessorAngle brackets used for system header files Double quotes used otherwisePath specifier is pathname
17、(which may include directory)identifying file whose content is to be substituted in place of include directive Examples int foo1();int foo2();#includeint main()foo1();head.hhello.cppg+Preprocessor:Defining Macros(宏)Define macros using#define directive When the preprocessor encounters this directive,
18、it replaces any occurrence of identifier in the rest of the code by replacement This replacement can be an expression,a statement,a block or simply anything Function macro definitions accept two special operators:#,#(concatenate)#define getmax(a,b)ab?a:b#define glue(a,b)a#b glue(c,out)test;cout test
19、;See program glue.cppPreprocessor:Conditional Compilation Conditionally include code through use of if-elif-else directives Conditional preprocessing block consists of:Example:Header Filenames Reason of using header filesAs programs grow larger(and make use of more files),it becomes increasingly ted
20、ious to have to forward declare every function you want to use that is defined in a different file.Namespaces Reasons of using namesapceTo simplify the writing of large programsTo help organize programs that combine pre-existing code from several companies To indicate which product(wanda)you want,us
21、ing double colon:A namespace example:stdStandard component of C+compilersC+Output with cout An example to print a stringcout:is an object defined in streamString:double quotation marks Insertion operator:operator:extract characters from the input streamThe value typed from the keyboard is eventually
22、 assigned to the variable:carrotsAssignment:Called Functions The example of called functions6.25 in parentheses is the input,called an argument or parameterThis example assigns the return value to the variable xFunction prototype of functions What a function prototype(函数原型/函数接口)does for functions is
23、 the samesameto that a variable declaration does for variablesYou can type the function prototype into your source code file yourselfYou can include the cmath(math.h on older systems)header file,which has the prototype in it The terminating semicolon in the prototype Identifies it as a statementMake
24、s it a prototype instead of a function headerBasic characteristics of functions Dont confuse the function prototypewith the function definitionFunction prototype describes the function interfaceThe definition includes the code for the functions workings Place a function prototype ahead of where you
25、first use the function Using#include directiveThe header files contain the prototypes.The library files contain the compiled code for the functions,Math functions in cmath An example shows the use of the library function sqrt()It provides a prototype by including the cmath file.Function Variations S
26、ome functions require more than one item of information Other functions take no arguments There also are functions that have no return valueUser-Defined Functions Two examplesmain()is a user-defined functionmul()is another user-defined functionOverview of Function Definition It has a header It has a
27、 bodyMultiple statements It accepts an argument It returns a value It requires a prototypeSummary What are the modules of C+programs called?functions What does the preprocessor directive do?What does the namespace do?What does the header do?What is the structure of function?Where does the prototype
28、put?Where does the program start to run?Summary C+provides two predefined objects:cout,cinThey are objects of the istream and ostream classes,in the iostream fileThese classes view input and output as streams of charactersThe insertion operator(),which is defined for the istream class,lets you extract information from the input stream C+can use the extensive set of C library functionsInclusion statement:#include Power function:pow(double);pow(double,double);Square root:sqrt(int);