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 int main () { cout 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 right LEFT 7 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 > console in, reading from keyboard cerr>i; coutname = “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 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 void odd (int a); void even (int a); int main () { ... }
Class Reference File VO ACSII Chart Inheritanc . are o can be mplates ang Overloading Operators 7 Dynamic Me ry Friend anced Class Syntax tt the c ANSI C++Library ++Reference Card 02002T7
Class Syntax class classname { public: classname(parms); // constructor ~classname(); // destructor member1; member2; protected: member3; ... private: member4; } objectname; // constructor (initializes variables) classname::classname(parms) { } // destructor (deletes variables) classname::~classname() { } public members are accessible from anywhere where the class is visible protected members are only accessible from members of the same class or of a friend class private members are accessible from members of the same class, members of the derived classes and a friend class constructors may be overloaded just like any other function. define two identical constructors with difference parameter lists Class Example class CSquare { // class declaration public: void Init(float h, float w); float GetArea(); // functions private: // available only to CSquare float h,w; } // implementations of functions void CSquare::Init(float hi, float wi){ h = hi; w = wi; } float CSquare::GetArea() { return (h*w); } // example declaration and usage CSquare theSquare; theSquare.Init(8,5); area = theSquare.GetArea(); // or using a pointer to the class CSquare *theSquare; theSquare->Init(8,5); area = theSquare->GetArea(); Inheritance Functions from a class can be inherited and reused in other classes. Multiple inheritance is possible. class CPoly { //create base polygon class protected: int width, height; public: void SetValues(int a, int b) { width=a; height=b;} }; class COutput { // create base output public: // class void Output(int i); }; void COutput::Output (int i) { cout function; template function; // ---------- function example --------- template T GetMax (T a, T b) { return (a>b?a:b); // return the larger } void main () { int a=9, b=2, c; float x=5.3, y=3.2, z; c=GetMax(a,b); z=GetMax(x,y); } // ----------- class example ----------- template class CPair { T x,y; public: Pair(T a, T b){ x=a; y=b; } T GetMax(); }; template T Pair::GetMax() { // implementation of GetMax function T ret; // return a template ret = x>y?x:y; // return larger return ret; } int main () { Pair theMax (80, 45); cout // read/write file #include // write file #include // read file File I/O is done from the fstream, ofstream, and ifstream classes. File Handles A file must have a file handle (pointer to the file) to access the file. ifstream infile; // create handle called // infile to read from a file ofstream outfile; // handle for writing fstream f; // handle for read/write Opening Files After declaring a file handle, the following syntax can be used to open the file void open(const char *fname, ios::mode); fname should be a string, specifying an absolute or relative path, including filename. ios::mode can be any number of the following and repeat: in Open file for reading out Open file for writing ate Initial position: end of file app Every output is appended at the end of file trunc If the file already existed it is erased binary Binary mode ifstream f; // open input file example f.open(“input.txt”, ios::in); ofstream f; // open for writing in binary f.open(“out.txt”, ios::out | ios::binary | ios::app); Closing a File A file can be closed by calling the handle’s close function f.close(); Writing To a File (Text Mode) The operator > can be used to read from a file. It works similar to cin. Fields are seperated in the file by spaces. ifstream f; // create file handle f.open(“input.txt”); // open file while (!f.eof()) // end of file test f >>a>>b>>c; // read into a,b,c I/O State Flags Flags are set if errors or other conditions occur. The following functions are members of the file object handle.bad() returns true if a failure occurs in reading or writing handle.fail() returns true for same cases as bad() plus if formatting errors occur handle.eof() returns true if the end of the file reached when reading handle.good() returns false if any of the above were true Stream Pointers handle.tellg() returns pointer to current location when reading a file handle.tellp() returns pointer to current location when writing a file // seek a position in reading a file handle.seekg(position); handle.seekg(offset, direction); // seek a position in writing a file handle.seekp(position); handle.seekp(offset, direction); direction can be one of the following ios::beg beginning of the stream ios::cur current position of the stream pointer ios::end end of the stream Binary Files buffer is a location to store the characters. numbytes is the number of bytes to written or read. write(char *buffer, numbytes); read(char *buffer, numbytes); Output Formatting streamclass f; // declare file handle // set output flags f.flags(ios_base::flag) possible flags dec fixed hex oct scientific internal left right uppercase boolalpha showbase showpoint showpos skipws unitbuf adjustfield left | right | internal basefield dec | oct | hex floatfield scientific | fixed f.fill() get fill character f.fill(ch) set fill character ch f.precision(numdigits) sets the precision for floating point numbers to numdigits f.put(c) put a single char into output stream f.setf(flag) sets a flag f.setf(flag, mask) sets a flag w/value f.width() returns the current number of characters to be written f.width(num) sets the number of chars to be written Dynamic Memory Memory can be allocated and deallocated // allocate memory (C++ only) pointer = new type []; int *ptr; // declare a pointer ptr = new int; // create a new instance ptr = new int [5]; // new array of ints // deallocate memory (C++ only) delete [] pointer; delete ptr; // delete a single int delete [] ptr // delete array // allocate memory (C or C++) void * malloc (nbytes); // nbytes=size char *buffer; // declare a buffer // allocate 10 bytes to the buffer buffer = (char *)malloc(10); // allocate memory (C or C++) // nelements = number elements // size = size of each element void * malloc (nelements, size); int *nums; // declare a buffer // allocate 5 sets of ints nums = (char *)calloc(5,sizeof(int)); // reallocate memory (C or C++) void * realloc (*ptr, size); // delete memory (C or C++) void free (*ptr); © 2002 The Book Company Storrs, CT refcard@gbook.org Information contained on this card carries no warranty. No liability is assumed by the maker of this card for accidents or damage resulting from its use. C++ Reference Card C/C++ Syntax, DataTypes, Functions Classes, I/O Stream Library Functions ACSII Chart Dec Char Dec Char Dec Char Dec Char 0 NUL 64 @ 128 Ç 192 └ 1 SOH 65 A 129 ü 193 ┴ 2 STX 66 B 130 é 194 ┬ 3 ETX 67 C 131 â 195 ├ 4 EOT 68 D 132 ä 196 ─ 5 ENQ 69 E 133 à 197 ┼ 6 ACK 70 F 134 å 198 ╞ 7 BEL 71 G 135 ç 199 ╟ 8 BS 72 H 136 ê 200 ╚ 9 TAB 73 I 137 ë 201 ╔ 10 LF 74 J 138 è 202 ╩ 11 VTB 75 K 139 ï 203 ╦ 12 FF 76 L 140 î 204 ╠ 13 CR 77 M 141 ì 205 ═ 14 SO 78 N 142 Ä 206 ╬ 15 SI 79 O 143 Å 207 ╧ 16 DLE 80 P 144 É 208 ╨ 17 DC1 81 Q 145 æ 209 ╤ 18 DC2 82 R 146 Æ 210 ╥ 19 DC3 83 S 147 ô 211 ╙ 20 DC4 84 T 148 ö 212 ╘ 21 NAK 85 U 149 ò 213 ╒ 22 SYN 86 V 150 û 214 ╓ 23 ETB 87 W 151 ù 215 ╫ 24 CAN 88 X 152 ÿ 216 ╪ 25 EM 89 Y 153 Ö 217 ┘ 26 SUB 90 Z 154 Ü 218 ┌ 27 ESC 91 [ 155 ¢ 219 █ 28 FS 92 \ 156 £ 220 ▄ 29 GS 93 ] 157 ¥ 221 ▌ 30 RS 94 ^ 158 ? 222 ? 31 US 95 _ 159 ƒ 223 ? 32 96 ` 160 á 224 α 33 ! 97 a 161 í 225 ß 34 “ 98 b 162 ó 226 Γ 35 # 99 c 163 ú 227 π 36 $ 100 d 164 ñ 228 Σ 37 % 101 e 165 Ñ 229 σ 38 & 102 f 166 ª 230 µ 39 ‘ 103 g 167 º 231 τ 40 ( 104 h 168 ¿ 232 Φ 41 ) 105 i 169 ? 233 Θ 42 * 106 j 170 ¬ 234 Ω 43 + 107 k 171 ½ 235 δ 44 , 108 l 172 ¼ 236 ∞ 45 - 109 m 173 ¡ 237 φ 46 . 110 n 174 « 238 ε 47 / 111 o 175 » 239 ∩ 48 0 112 p 176 ? 240 ≡ 49 1 113 q 177 ▒ 241 ± 50 2 114 r 178 ▓ 242 ≥ 51 3 115 s 179 │ 243 ≤ 52 4 116 t 180 ┤ 244 ? 53 5 117 u 181 ╡ 245 ? 54 6 118 v 182 ╢ 246 ÷ 55 7 119 w 183 ╖ 247 ≈ 56 8 120 x 184 ╕ 248 ° 57 9 121 y 185 ╣ 249 ? 58 : 122 z 186 ║ 250 · 59 ; 123 { 187 ╗ 251 √ 60 126 ~ 190 ╛ 254 ■ 63 ? 127 ? 191 ┐ 255 Overloading Operators Like functions, operators can be overloaded. Imagine you have a class that defines a square and you create two instances of the class. You can add the two objects together. class CSquare { // declare a class public: // functions void Init(float h, float w); float GetArea(); CSquare operator + (CSquare); private: // overload the ‘+’ operator float h,w; } // function implementations void CSquare::Init(float hi, float wi){ h = hi; w = wi; } float CSquare::GetArea() { return (h*w); }// implementation of overloaded operator CSquare CSquare::operator+ (CSquare cs) { CSquare temp; // create CSquare object temp.h = h + cs.h; // add h and w to temp.w = w + cs.w; // temp object return (temp); } // object declaration and usage CSquare sqr1, sqr2, sqr3; sqr1.Init(3,4); // initialize objects sqr2.Init(2,3); sqr3 = sqr1 + sqr2; // object sqr3 is now (5,7) Class Reference Friend Classes/Functions Friend Class Example class CSquare; // define CSquare class CRectangle { int width, height; public: void convert (CSquare a); }; class CSquare { // we want to use the private: // convert function in int side; // the CSquare class, so public: // use the friend keyword void set_side (int a) { side=a; } friend class CRectangle; }; void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } // declaration and usage CSquare sqr; CRectangle rect; // convert can be sqr.set_side(4); // used by the rect.convert(sqr); // rectangle class Friend Functions A friend function has the keyword friend in front of it. If it is declared inside a class, that function can be called without reference from an object. An object may be passed to it. /* change can be used anywhere and can have a CRect object passed in */ // this example defined inside a class friend CRect change(CRect); CRectangle recta, rectb; // declaration rectb = change(recta); // usage Advanced Class Syntax Static Keyword static variables are the same throughout all instances of a class. static int n; // declaration CDummy::n; // reference Virtual Members Classes may have virtual members. If the function is redefined in an inherited class, the parent must have the word virtual in front of the function definition This keyword The this keyword refers to the memory location of the current object. int func(this); // passes pointer to // current object Class TypeCasting reinterpret_cast (expression); dynamic_cast (expression); static_cast (expression); const_cast (expression); Expression Type The type of an expression can be found using typeid. typeid returns a type. typeid(expression); ANSI C++ Library Files The following files are part of the ANSI C++ standard and should work in most compilers