C程序設計教學課件:Chapter One From C to C_第1頁
C程序設計教學課件:Chapter One From C to C_第2頁
C程序設計教學課件:Chapter One From C to C_第3頁
C程序設計教學課件:Chapter One From C to C_第4頁
C程序設計教學課件:Chapter One From C to C_第5頁
已閱讀5頁,還剩69頁未讀 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

1、C+ ProgrammingChaper 1 From C to C+Index1. C+ foundation1.1 Data Type1.2 Operators1.3 Controlling Execution1.4 C+ input/output2 Functions2.1 Function Introduction2.2 Storage Allocation2.3 inline Functions2.4 Default Arguments2.5 Overloading Functions3 Pointers and references3.1 Pointers introduction

2、3.2 Pointers and Constants3.3 Pointers and Arrays3.4 Pointers and Functions3.5 The new and delete operators3.6 References1.1 Data TypesData types define the way you use storage (memory) in the programs you write. By specifying a data type, you tell the compiler how to create a particular piece of st

3、orage, and also how to manipulate that storage.1.1 Data TypesData TypesBasic built-in typesintcharbooltype *voidstructunionenum classfloatdoubleUser-define types1.2 OperatorsArithmetic OperatorsAuto increment and decrementRelational OperatorsLogical OperatorsAssignment OperatorsThe ternary operator

4、( ? : )Bitwise OperatorsShift operators1.3 Controlling Executionwhile, do-while, and for control looping. while: A statement repeats until the controlling expression evaluates to false. The form of a while loop is:while( expression) statementdo-whileThe form of do-while isdo statementwhile(expressio

5、n); The do-while is different from the while because the statement always executes at least once, even if the expression evaluates to false the first time. In a regular while, if the conditional is false the first time the statement never executes.1.3 Controlling ExecutionforThe form of the for loop

6、 is: for( initialization; conditional; step) statementAny of the initialization, conditional, or step expressions may be empty. The initialization code executes once at the very beginning. The conditional is tested before each iteration (if it evaluates to false at the beginning, the statement never

7、 executes). At the end of each loop, the step executes.1.3 Controlling Executionbreak and continue Inside the body of any of the looping constructs while, do-while, or for, you can control the flow of the loop using break and continue. break quits the loop without executing the rest of the statement

8、s in the loop. continue stops the execution of the current iteration and goes back to the beginning of the loop to begin a new iteration.1.3 Controlling Executionif-else The if-else statement can exist in two forms: with or without the else. The two forms are:if( expression ) statementor:if( express

9、ion ) statementelse statement1.3 Controlling Execution1.3 Controlling Executionswitch A switch statement selects from among pieces of code based on the value of an integral expression. Its form is:switch( selector ) case integral-value1 : statement; break; case integral-value2 : statement; break; ca

10、se integral-value3 : statement; break; case integral-value4 : statement; break; case integral-value5 : statement; break; (.) default: statement;1.3 Controlling ExecutionSelector is an expression that produces an integral value. The switch compares the result of selector to each integral value. If it

11、 finds a match, the corresponding statement (simple or compound) executes. If no match occurs, the default statement executes.1.3 Controlling Executiongoto: the goto keyword is supported in C+, since it exists in C.#include int main() long val = 0; for(int i = 1; i 1000; i+) for(int j = 1; j 47000)

12、goto bottom; / Break would only go to the outer for bottom: / A label cout val is used for input, is used for output. Both operators recognize the data type supplied, so no format string is necessary.1.4 C+ Input/outputExample:#include void main() int i; float f; char c; cinifc; cout The integer is

13、in the float is fn the char is cendl; 2.1Function introduction Definitions of Functions Function syntax: type-of-return function-name(argument-list) /body The argument list is a way for functions to communicate with each other by passing information.2.1 Function introductionPrototypesIn a function p

14、rototype, the argument list contains the types of arguments that must be passed to the function and identifiers for the arguments. The order and type of the arguments must match in the declaration, definition, and function call.In C+, prototypes are required and every function must be declared prior

15、 to being used. A return type must be specified.2.1 Function introductionFunction CallsWhen a function is called, temporary memory is set up.Then the flow of control passes to the first statement in the functions body. The called functions body statements are executed until one of these occurs: retu

16、rn statement (with or without a return value), or closing brace of function body.Then control goes back to where the function was called.2.2 Storage AllocationWhen creating a variable, you have a number of options to specify the lifetime of the variable, how the storage is allocated for that variabl

17、e, and how the variable is treated by the compiler.Global variables are defined outside all function bodies and are available to all parts of the program.Local variables are often called automatic variables because they automatically come into being when the scope is entered and automatically go awa

18、y when the scope closes. 2.2 Storage AllocationstaticIf you want a value to be extant throughout the life of a program, you can define a functions local variable to be static and give it an initial value. The initialization is performed only the first time the function is called, and the data retain

19、s its value between function calls. 2.2 Storage AllocationExample: include void func(); int n = 1; void main() static int a; int b = -10; cout “a:” a “;b:” b “;n:” n endl; b += 4; func(); cout “a:” a “;b:” b “;n:” n endl; n += 10; func(); void func() static int a = 2; int b=5; a += 2; n += 12; b +=

20、5; cout “a:” a “;b:” b “;n:” n endl;Output: a:0;b:-10;n:1 a:4;b:10;n:13 a:0;b:-6;n:13 a:6;b:10;n:352.3 Inline FunctionsThe keyword inline can be used in a function declaration to request that a function be expanded “inline” . That is, that each occurrence of a call of the function be replaced with t

21、he code that implements the function. Remark: The compiler, for various reasons, may not be able to honor the request.2.3 Inline FunctionsExample:#include inline int isnumber(char);void main() char c; while( c = cin.get() != n) if(isnumber(c) cout “You entered a digit n”; else cout = 0 & ch = 9) ? 1

22、:0;2.3 Inline FunctionsAssuming that the compiler honors the request to expand isnumber inline, no function call occurs at the line if(isnumber(c)Because isnumber is an inline function, the compiler replaces the lineif(isnumber(c) with the code that implements isnumber.2.4 Default ArgumentsA default

23、 argument is a value given in the declaration that the compiler automatically inserts if you dont provide a value in the function call.Example:int add(int x=5,int y=6) return x+y;void main(void) add(10,20); /10+20 add(10); add(); 2.4 Default ArgumentsRules :First, only trailing arguments may be defa

24、ulted. That is, you cant have a default argument followed by a non-default argument. Second, once you start using default arguments in a particular function call, all the subsequent arguments in that functions argument list must be defaulted.Third, default arguments are only placed in the declaratio

25、n of a function (typically placed in a header file). 2.4 Default ArgumentsExample 1:int add(int x,int y=5,int z=6); int add(int x=1,int y=5,int z); int add(int x=1,int y,int z=6); Example 2:int add(int x,int y=5,int z=6); add(10,12,1); add(); add(12); add(1,12); /right/wrong/wrong/right/wrong/right/

26、wrong2.5 Overloading FunctionsC+ permits identically named functions within the same scope if they can be distinguished by the number, data types and order of its arguments. If there are multiple definitions of a function, is said to be overloaded.Example 1:int add(int x, int y); float add(float x,

27、float y); Example 2:int add(int x, int y); int add(int x, int y, int z); / type of parameters are different/ numbers of parameters are different2.5 Overloading FunctionsExample 3:int add(int x,int y);int add(int a,int b); int add(int x,int y);void add(int x,int y); /wrong/wrongExample 4:#include usi

28、ng namespace std;void print(int a);void print(double a);int main() int x=8; double y=8; print(x); print(y); return 0;void print (int a) coutaendl;void print (double a) coutaendl;2.5 Overloading Functions2.5 Overloading FunctionsRemarks:Overloaded functions are used to give a common name to similar b

29、ehavior on different data types.Be careful if we use both default arguments and overloading functions.2.5 Overloading FunctionsExample 5:int abs(int x) int abs(int x, int y=10) abs(-100); /Which function should be invoked?Exercise#includevoid fn(int n)int x=5;static int y=10;if(n0)+x;+y;coutx,yendl;

30、void main()int m=1;fn(m); fn(m);Output:6 11 6 123.1 Pointers introductionSince your program lives in memory while its being run, every element of your program has an address.There is an operator in C and C+ that will tell you the address of an element. This is the & operator. All you do is precede t

31、he identifier name with & and it will produce the address of that identifier. So pointer is the address of the element in a program.3.1 Pointers introductionDefine PointersExample:int i; int *i_pointer=&i; *i_pointer=3;20003i_pointer*i_pointeri2000memoryvariable ivariable jvariable i_pointer36200020

32、00200430103.1 Pointers introductionRemarks:If a pointer is initialized by an address of a variable, the variable must be defined before initialized, and the type must match, too.A pointer can be initialized by another pointer, which is initialized already.The type of a pointer means the type of the

33、variable that the pointer points to. The type of the pointer itself is unsigned int.Only void pointer can point to any type of data.3.1 Pointers introductionExample:int iCount=26;int* iPtr;*iPtr=56; *iPtr=&iCount; void * vptr = iptr; iptr = vptr; /wrong/wrong/right/wrong3.2 Pointers and constantsWhe

34、n using const with pointers, you have two options: const can be applied to what the pointer is pointing to, or the const can be applied to the address stored in the pointer itself.3.2 Pointers and constantsPointer to Const: if you want to prevent any changes to the element you are pointing to, you w

35、rite a definition like this:const int* p; /orint const* p;Question: A pointer to const can point to a variable, but a pointer to variable can not point to a const if the pointer is not a pointer to const, why?3.2 Pointers and constantsExample: const int a = 78; const int b=28; int c=18; const int *p

36、i = &a; *pi = 85; pi = &b; *pi = 90; pi = &c; *pi = 88; c = 98;3.2 Pointers and constantsConst Pointer: to 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 pointer pointing to

37、 is not const.3.2 Pointers and constantsExample:char* const pc=“asdf”; pc=“dfgh”; const int b=30;int* const pi=&b;Given the definition“ int * const pi=&b;” means pi is const, but *pi is not const. 3.2 Pointers and constantsConst Pointer to ConstYou can also make a const pointer to a const object usi

38、ng either of two legal forms:int d = 1;const int* const x = &d; Now neither the pointer nor the object can be changed.3.2 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; ”

39、means both cpc and *cpc are const. 3.3 Pointers and Arrays Addition and Subtraction of Pointers If 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 int type pointer means 4; 1 a

40、ddition to a float type pointer means 4; 1 addition to a double type pointer means 8;3.3 Pointers and Arrayspapa-2pa-1pa+1pa+2pa+3*(pa-2)*pa*(pa+1)*(pa+2)*(pa+3)*(pa-1)short int *papb-1pbpb+1pb+2*(pb-1)*pb*(pb+1)*(pb+2)long int *pb3.3 Pointers and ArraysArrays are a kind of composite type because th

41、ey allow you to clump a lot of variables together, one right after the other, under a single identifier name.Remarks:The memory address location of the elements in the array is consecutive.The name of the array is the memory address location of the first element in the array.The name of the array is

42、 a constant.3.3 Pointers and Arrays Pointer to Arrays Example: int a10, *iPtr; iPtr=&a0; /or iPtr=a; the value of the i+1th item: ai=*(a+i)=iPtri=*(iPtr+i) The address of the i+1th item: &ai=a+i=iPtr+i=&iPtri Remark:a+ is illegal, because a is the address of the array, and it is const.3.3 Pointers a

43、nd ArraysArray PointersExample:#include 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;/pointer array p_line0=line1;/initializationp_line1=line2;p_line2=line3;3.3 Pointers and Arrays/output the m

44、atrix coutMatrix test: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 3.3 Pointers and ArraysArray Argument: the fact that naming an array produces its starting address turns out to be quite importa

45、nt when you want to pass an array to a function. If 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 modify an array, youre alw

46、ays modifying the outside object.3.3 Pointers and ArraysExample:#include void sum(int array,int n) int sum=0; for(int i=0;in;i+) sum += *array; array+; cout sum endl; void main() int a10=1,2,3,4,5,6,7,8,9,10; sum(a,10); Output: 55sum10983210067F010返回地址0067F010arraysum數組amain3.4 Pointers and function

47、s Pointer Arguments Passing data by pointer will result the change of the arguments.3.4 Pointers and functions#include void swap(int *, int*); void main() int a=3,b=8; cout “a=” a “,” “b=”bendl; swap(&a,&b); cout “a=” a “,” “b=”bendl; void swap(int *x, int* y) int temp = *x; *x=*y; *y=temp; Output:

48、a=3,b=8 a=8,b=330067F006 a80067F010 b返回地址0067F006x0067F010ytempmainswap棧3383.4 Pointers and functions Pointer to Functions A pointer can not only point to the variable in a program, but also point to a function in a program. Syntax: type-of-return (* function-name) (argument-list);Example: int (*fun

49、c)(char a,char b); int *func(char a,char b); /Error: its a function, not a pointer to function.3.4 Pointers and functionsExample:How to user pointers to functions. int fn1(char x,char y); int *fn2(char x,char y); int fn3(int a); int (*fp1)(char a,char b); int (*fp2)(int s); fp1=fn1; fp1=fn2; fp2=fn3

50、; fp2=fp1; fp2=fn3(5);/right/wrong/right/wrong/wrong3.4 Pointers and functionsExample: Why to use pointers to functions.#include #include double sigma(double(*func)(double),double dl,double du) double dt=0.0; for(double d=dl;ddu;d+=0.1) dt+=func(d); return dt;void main() double dsum; dsum=sigma(sin,

51、0.1,1.0); cout The sum of sim from 0.1 to 1.0 is dsum endl; dsum=sigma(cos,0.5,3.0); cout The sum of cos from 0.5 to 3.0 is dsum endl;Output:The sum of sim from 0.1 to 1.0 is 5.01388The sum of cos from 0.5 to 3.0 is -2.446453.5 The new and delete OperatorsNew and DeleteThe new, new , delete, and del

52、ete operators are used to 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 . New, new , delete, and delete are built-in operators while malloc and free are

53、C library functions.3.5 The new and delete OperatorsExample:#include #include /for strlen int main() char* str = Idle hands are the devils workshop.; int len = strlen(str); /get length of str char* ptr; /make a pointer to char ptr = new charlen+1; /set aside memory: string + 0 strcpy(ptr, str); /cop

54、y str to new memory area ptr cout ptr= ptr endl; /show that ptr is now in str delete ptr; /release ptrs memory return 0; pointerKeywordVariables lenghtThe type of variable3.6 ReferencesA reference, signaled by the ampersand &, provides an alternative name for storage.Example:int x;int& ref = x;Remar

55、k: both x and ref are stored in the same int storage.Example:#include void main() int intOne; int& rInt=intOne; intOne=5; cout intOne:intOneendl; cout rInt:rIntendl; cout &intOne:&intOneendl; cout &rInt:&rIntendl; int intTwo=8; rInt=intTwo; cout intOne:intOneendl; cout intTwo:intTwoendl; cout rInt:r

56、Intendl; cout &intOne:&intOneendl; cout &intTwo:&intTwoendl; cout &rInt:&rIntendl;3.6 References Call by Reference If we designate a parameter as a reference parameter using the ampersand &, we obtain call by reference in which the reference parameter refers to the actual argument passed to the function and not to a copy of the

溫馨提示

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

評論

0/150

提交評論