正在加载图片...
C++Reference Card ©2002 Greg Book Key C++Program Structure Control Structures unctions and )y ynta Identifiers hese are ANSI C annot be used as vari on (de-w w.o oco Data Types Operators ae8econe sign type name nct 9n-128t0127 e ca ay by gned-2 ,29 Console Input/Output n factora1(n-11 tum (1) Initialization of Variables User Defined DataTypes typing 2g28 Namespaces ifiers under a nam Preprocessor Directives Character Strings Exceptions 三C++ Reference Card © 2002 Greg Book Key switch – keyword, reserved “Hello!” – string // comment – commented code close() – library function main – variable, identifier variable – placeholder in syntax if (exression) - syntax statement; C++ Program Structure // my first program in C++ #include <iostream.h> int main () { cout << “Hello World!”; return 0; } // single line comment /* multi-line comment */ Identifiers These are ANSI C++ reserved words and cannot be used as variable names. asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t Operators priority/operator/desc/ASSOCIATIVITY 1 :: scope LEFT 2 () parenthesis LEFT [ ] brackets LEFT -> pointer reference LEFT . structure member access LEFT sizeof returns memory size LEFT 3 ++ increment RIGHT — decrement RIGHT ~ complement to one (bitwise) RIGHT ! unary NOT RIGHT & reference (pointers) RIGHT * dereference RIGHT (type) type casting RIGHT + - unary less sign RIGHT 4 * multiply LEFT / divide LEFT % modulus LEFT 5 + addition LEFT - subtraction LEFT 6 << bitwise shift left LEFT >> bitwise shift right LEFT 7 < less than LEFT <= less than or equal LEFT > greater than LEFT >= greater than or equal LEFT 8 == equal LEFT != not equal LEFT 9 & bitwise AND LEFT ^ bitwise NOT LEFT | bitwise OR LEFT 10 && logical AND LEFT || logical OR LEFT 11 ? : conditional RIGHT 12 = assignment += add/assign -= subtract/assign *= multiply/assign /= divide/assign %= modulus/assign >>= bitwise shift right/assign <<= bitwise shift left/assign &= bitwise AND/assign ^= bitwise NOT/assign |= bitwise OR/assign 13 , comma User Defined DataTypes typedef existingtype newtypename; typedef unsigned int WORD; enum name{val1, val2, ...} obj_name; enum days_t {MON,WED,FRI} days; union model_name { type1 element1; type2 element2; ... } object_name; union mytypes_t { char c; int i; } mytypes; struct packed { // bit fields unsigned int flagA:1; // flagA is 1 bit unsigned int flagB:3; // flagB is 3 bit } Console Input/Output [See File I/O on reverse for more about streams] C Style Console I/O stdin – standard input stream stdout – standard output stream stderr – standard error stream // print to screen with formatting printf(“format”, arg1,arg2,...); printf(“nums: %d, %f, %c”, 1,5.6,’C’); // print to string s sprintf(s,”format”, arg1, arg2,...); sprintf(s,”This is string # %i”,2); // read data from keyboard into // name1,name2,... scanf(“format”,&name1,&name2, ...); scanf(“%d,%f”,var1,var2); // read nums // read from string s sscanf(“format”,&name1,&name2, ...); sscanf(s,“%i,%c”,var1,var2); C Style I/O Formatting %d, %i integer %c single character %f double (float) %o octal %p pointer %u unsigned %s char string %e, %E exponential %x, %X hexadecimal %n number of chars written %g, %G same as f for e,E C++ console I/O cout<< console out, printing to screen cin>> console in, reading from keyboard cerr<< console error clog<< console log cout<<“Please enter an integer: ”; cin>>i; cout<<“num1: ”<<i<<“\n”<<endl; Control Characters \b backspace \f form feed \r return \’ apostrophe \n newline \t tab \nnn character #nnn (octal) \” quote \NN character #NN (hexadecimal) Control Structures Decision (if-else) if (condition) { statements; } else if (condition) { statements; } else { statements; } if (x == 3) // curly braces not needed flag = 1; // when if statement is else // followed by only one flag = 0; // statement Repetition (while) while (expression) { // loop until statements; // expression is false } Repetition (do-while) do { // perform the statements statements; // as long as condition } while (condition); // is true Repetition (for) init - initial value for loop control variable condition - stay in the loop as long as condition is true increment - change the loop control variable for(init; condition; increment) { statements; } Bifurcation (break, continue, goto, exit) break; // ends a loop continue; // stops executing statements // in current iteration of loop cont- // inues executing on next iteration label: goto label; // execution continues at // label exit(retcode); // exits program Selection (switch) switch (variable) { case constant1: // chars, ints statements; break; // needed to end flow case constant2: statements; break; default: statements; // default statements } Preprocessor Directives #define ID value // replaces ID with //value for each occurrence in the code #undef ID // reverse of #define #ifdef ID //executes code if ID defined #ifndef ID // opposite of #ifdef #if expr // executes if expr is true #else // else #elif // else if #endif // ends if block #line number “filename” // #line controls what line number and // filename appear when a compiler error // occurs #error msg //reports msg on cmpl. error #include “file” // inserts file into code // during compilation #pragma //passes parameters to compiler Namespaces Namespaces allow global identifiers under a name // simple namespace namespace identifier { namespace-body; } // example namespace namespace first {int var = 5;} namespace second {double var = 3.1416;} int main () { cout << first::var << endl; cout << second::var << endl; return 0; } using namespace allows for the current nesting level to use the appropriate namespace using namespace identifier; // example using namespace namespace first {int var = 5;} namespace second {double var = 3.1416;} int main () { using namespace second; cout << var << endl; cout << (var*2) << endl; return 0; } Exceptions try { // code to be tried... if statements statements; // fail, exception is set throw exception; } catch (type exception) { // code in case of exception statements; } Initialization of Variables type id; // declaration type id,id,id; // multiple declaration type *id; // pointer declaration type id = value; // declare with assign type *id = value; // pointer with assign id = value; // assignment Examples // single character in single quotes char c=‘A’; // string in double quotes, ptr to string char *str = “Hello”; int i = 1022; float f = 4.0E10; // 4^10 int ary[2] = {1,2} // array of ints const int a = 45; // constant declaration struct products { // declaration char name [30]; float price; } ; products apple; // create instance apple.name = “Macintosh”; // assignment apple.price = 0.45; products *pApple; // pointer to struct pApple->name = “Granny Smith”; pApple->price = 0.35; // assignment Data Types Variable Declaration special class size sign type name; special: volatile class: register, static, extern, auto size: long, short, double sign: signed, unsigned type: int, float, char (required) name: the variable name (required) // example of variable declaration extern short unsigned char AFlag; TYPE SIZE RANGE char 1 signed -128 to 127 unsigned 0 to 255 short 2 signed -32,768 to 32,767 unsigned 0 to 65,535 long 4 signed -2,147,483,648 to 2,147,483,647 unsigned 0 - 4,294,967,295 int varies depending on system float 4 3.4E +/- 38 (7 digits) double 8 1.7E +/- 308 (15 digits) long double 10 1.2E +/- 4,932 (19 digits) bool 1 true or false wchar_t 2 wide characters Pointers type *variable; // pointer to variable type *func(); // function returns pointer void * // generic pointer type NULL; // null pointer *ptr; // object pointed to by pointer &obj // address of object Arrays int arry[n]; // array of size n int arry2d[n][m]; // 2d n x m array int arry3d[i][j][k]; // 3d i x j x k array Structures struct name { type1 element1; type2 element2; ... } object_name; // instance of name name variable; // variable of type name variable.element1; // ref. of element variable->element1; // reference of pointed to structure Character Strings The string “Hello” is actually composed of 6 characters and is stored in memory as follows: Char H e l l o \0 Index 0 1 2 3 4 5 \0 (backslash zero) is the null terminator character and determines the end of the string. A string is an array of characters. Arrays in C and C++ start at zero. str = “Hello”; str[2] = ‘e’; // string is now ‘Heelo’ common <string.h> functions: strcat(s1,s2) strchr(s1,c) strcmp(s1,s2) strcpy(s2,s1) strlen(s1) strncpy(s2,s1,n) strstr(s1,s2) Functions In C, functions must be prototyped before the main function, and defined after the main function. In C++, functions may, but do not need to be, prototyped. C++ functions must be defined before the location where they are called from. // function declaration type name(arg1, arg2, ...) { statement1; statement2; ... } type – return type of the function name – name by which the function is called arg1, arg2 – parameters to the function statement – statements inside the function // example function declaration // return type int int add(int a, int b) { // parms int r; // declaration r = a + b; // add nums return r; // return value } // function call num = add(1,2); Passing Parameters Pass by Value function(int var); // passed by value Variable is passed into the function and can be changed, but changes are not passed back. Pass by Constant Value function(const int var); Variable is passed into the function but cannot be changed. Pass by Reference function(int &var); // pass by reference Variable is passed into the function and can be changed, changes are passed back. Pass by Constant Reference function(const int &var); Variable cannot be changed in the function. Passing an Array by Reference It’s a waste of memory to pass arrays and structures by value, instead pass by reference. int array[1]; // array declaration ret = aryfunc(&array); // function call int aryfunc(int *array[1]) { array[0] = 2; // function return 2; // declaration } Default Parameter Values int add(int a, int b=2) { int r; r=a+b; // b is always 2 return (r); } Overloading Functions Functions can have the same name, and same number of parameters as long as the parameters of are different types // takes and returns integers int divide (int a, int b) { return (a/b); } // takes and returns floats float divide (float a, float b) { return (a/b); } divide(10,2); // returns 5 divide(10,3); // returns 3.33333333 Recursion Functions can call themselves long factorial (long n) { if (n > 1) return (n * factorial (n-1)); else return (1); } Prototyping Functions can be prototyped so they can be used after being declared in any order // prototyped functions can be used // anywhere in the program #include <iostream.h> void odd (int a); void even (int a); int main () { ... }
向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有