Вы находитесь на странице: 1из 16

INDEX UNIX MANUAL C++ REFERENCE Fundamentals Data Types Escape Sequences Literals Math Functions And Operators

Cctype Library Functions Libraries Programming Structures Strings And Input-Output Random Numbers Enum Storage Classes And Scope Arrays Pointers And References Cstring Library Struct And Classes New And Delete Operator Overloading ================================================================= //UNIX MANUAL cp <filename> <filename> mv <source> <dest> rm <filename> more <filename> grep <string> <filename> ls [-l] set path=($path /usr/users/edu1999/lottini/calcolo2) set g++ <nomefile.cc> //crea a.out g++ -o <nomeprog.exe> <nomefile> //crea nomeprog.exe //C++ REFERENCE: //FUNDAMENTALS int main() { //one-line comment /* long comment */ ... ... return 0; } #include <iostream> //outside main() using namespace std; //outside main() int a; string b; //needs #include <string> cout << "string" << "\n"; cin >> stringname; float c,d; cin << d << c; const <datatype> <constname> = <value>;

const myString = "firstpart " "secondpart" "thirdpart"; #include "/usr/include/math.h" //must be included this way under our Lin ux! #include <cmath> pow(base, power); //needs math functions double a = <initializing expression>; cout << something << endl; // end of line #include <cassert> assert(condition); //breaks program if condition is false

exit(1); //quits program with error code 1 #define <meta-const-name> #ifdef <name> //or #ifndef... ... #endif //DATA TYPES char bool // true or false int double float unsigned short long long double //ESCAPE SEQUENCES \n \t \v \f \a \\ \' \" \ooo \hhh //LITERALS 12 //decimal 0123 //octal 0x12FD //hexadecimal true - false //bool twos-complement (binary numbers): 1. write absolute value in binary 2. invert all bits 3. add 1 //MATH FUNCTIONS AND OPERATORS endline horiz. tab vert. tab form feed beep \ ' " char with octal ooo char with hex hhh

+ * / //integer result if integers operands! (use: a = (b+0.0)/c or si milar to suppress that behavior) % modulus sin(a) cos(a) tan(a) sqrt(a) log(a) abs(a) asin(a) acos(a) atan(a) log10(a) pow(a,b) == > < != >= <= && //comparison //true if operands different

//logical AND //logical OR !(bool) //logical NOT //Operators priority (from highest to lowest): (), + - (unary), * / %, + - (binary), < <= > >=, == !=, &&, //Operators associativity -, ... are left-associative //to allow a = b - c - d; = is right-associative //to allow a = b = c; //Shortcuts a += 4 // -=, *= etc... a++, a-- //returns the old value ++a, --a //returns the new value cast <type>(expression); //seems doesn't work, anyway... a = static cast<type>(expression); //CCTYPE LIBRARY #include <cctype> isalpha(char) isalnum(c) isdigit(c) isgraph(c) iscntrl(c) islower(c) isupper(c) isspace(c) ispunct(c) isprint(c) //all of return type bool toupper(c) tolower(c) //return type char

//FUNCTIONS [#includes and other general stuff] [function prototypes] (prototype can also be encapsulated in another function, when it is called only from that function - and the body has to follow externally!) [main] [function definition (body)] //prototype: <return-type (or void)> <function name> (<argtype>, <argtype> ... <void if no arguments>); double maximum(double, double); //in main() or elsewhere, to call: <function name>(argument1, argument2...) a = maximum(d, f); //definition: <return-type> <function name>(<argtype> <argname>, ...){ //... //... return <value>; //"return;" if void } double maximum(double a, double b){ return (a>b ? a : b); } //Inline functions: inline <type> <name>(arglist) {function body} //NO ";"!!! inline int max(int a, int b){return a>b ? a : b} //Arguments by REFERENCE (no explicit pointer fashion) <type> <name> (<type> &variable_name, ...){ //I am accessing original variable and not copy! } //Defaults: (in Prototype!!!) <type> <nome>(int = 2, char = 'f'); //rigthmost elements get their defau lts first //Function Overloading int square( int x) {return x * x;} float square(float x) {return x * x;} int main(){ int a=3; float b=3.0; cout << square(a) << endl ; cout << square(b) << endl; } //Function Template template <class V> V square(V value1){ return value1 * value1; }

int main() { int a=4; float b = 1.22; cout << square(a) << endl; cout << square(b) << endl; } //LIBRARIES f.h //header file: prototypes f.cpp //implementation (definitions) f.doc //header file + large comments #include "f.h" //PROGRAMMING STRUCTURES //seems they need "#include <cstdlib>" to "break;" !!! //IF if (bool-condition) statement; else statement; -------if (cond) { stat1; stat2; ... statn; } else{ stat1; ... statn; } -------if (cond) stat; -------if (cond1) stat1; else if (cond2) stat2; else if (cond3) stat3; ... ... else statn+1; -------//Immediate if:

<bool-expr> ? <truepart> : <falsepart> a = (b > 0 ? b : -b); //FOR for(initialization; loop-condition; increment-expression) statement; ---------for(ini; l-c; i-e){ stat1; stat2; ... [break;] //optional ... statn; } ---------for (;;){ <block1> break; <block2> } //SWITCH switch (integer-expression) { case const1: stat1; //don't use {} for multiple statements!!! stat2; stat3; break; //no automatic exit! case const2: <the same> case const3: <the same> ... default: <no need for break here!> } ---------switch (i-e) { case 1: case 2: //here code to be executed in cases 1 OR 2... //etc... } //WHILE-DO do{ stat1; stat2; ...

} while (bool-expr); --------do unique-stat; while (bool-expr); --------while (bool-expr) stat; --------while (bool-expr){ stat1; stat2; stat3; ... } //STRINGS AND INPUT-OUTPUT

//block executed at least once //end of loop when condition is false

//no execution if bool-expr initially false

#include <string> //data type STRING (class) #include <cstring> //basic string operations (ar arrays of chars) char(number); //returns the char with ANSI code number string mys = "abc"; cout << mys; char myc = mys[1]; mys.size(); //returns 3 istream >> str; //usually cin; stops at whitespace and fills buffer getline(istream, str); //stops at newline str.empty(); //returns bool news = str1 + str2; //concatenates them str.substr(pos, numchars); str.insert(pos, substr); str.remove(pos, numchars); str.find("pattern", start_pos); //returns int //valid with strings: == >= <= != cin >> ch //non whitespace cin.get(ch) //whitespace also cin.good() //bool cin.bad() //bool cin.fail() //bool cin.clear() cin.ignore(n, 'delimiter-char') cout << printable-expression

cout.put(char) cout << COMMAND //where command can be: flush endl fixed scientific showpoint noshowpoint showpos noshowpos boolalhpa noboolalhpa setprecision(n) setw(n) left right setiosflags(ios::left); setfill('X') //X's in place of blanks [seem to require "#include <iomanip>" and "using std::XXX" with XXX = setw, ostream, istream, cout, endl...] //RANDOM NUMBERS <cstdlib> <ctime> <iostream> <math> <cmath> <iomanip> ... rand(); //pseudornd 0-32767 srand(seed); //sets new seed for next rand() calls //usually srand(time(0)) for almost-true-random numbers i = rand() % 6 + 1 //ENUM enum myenum{const1, const2, const3}; //starts at zero enum myenum{const1 = 4, const2, const3}; myenum ThisEnum; ThisEnum = const2; //STORAGE CLASSES AND SCOPE auto float x,y; //new vars created every time function is called register int b; //tries to put b in high-speed register (only local vari ables) static long c; //locals, one-time initialized! extern double d; //global variables (declared outside functions and main ) //"+1" //"1" //"true" //"1"

//Scope: file function block (prototype) ::x = 3; //to access global x while there exists a local x //ARRAYS //arrays int c[n]; c[0] = 2; c[n-1] = 3; //last element //initializers int n[5] = {1,2,3,4,5}; int n[5] = {0}; //all set to zero int n[] = {6,7,8,9,10} //initialization sets array size char string[] = "hi"; char s[] = {'h', 'i', '\0'} //must add the null character! s[1] == i; //yelds true cin >> s; //but cax exceed size and write beyond permitted memory cin >> setw(20) >> s; //fix that problem cin.getline(array, size [, delimiter-character]); cout << s; //arrays as function arguments int myArr[24]; function(myArr, 24); //whole array is passed by ref, array elements by v alue! void function(int b[], int size){ prototype b[size-1] = ... ... } //array search 1. bubblesort 2. binary... //Multi-dimensional arrays int b[n][m] = {{1,2,3,..},{1,2,3...},...,{1,2,3,...}}; = {{1},{1,2}}; //initialization and default... int a = b[0][2]; function(b[1],size_of_free_subscript); //POINTERS AND REFERENCES int *myptr; //contain 0,NULL or and address int b; myptr = &var; //puts the address of var into myptr *myptr = 4; //now var contains 4 &*myptr = *&myptr = myptr; //they cancel each other //Call by reference with pointers void do2(int *); int main(){ int a=2; //only "int [], int" in

do2(&a); //now a contains 4 } void do2(int *numptr){ *numptr *= 2; } //Const keyword: ify it. With pointers: int *const myptr const int *myptr const int *const variable cannot change: used when function does not mod = &x; //constant pointer to non const integer = &x; // pointer to const int myptr = &x; //const pointer to const int

sizeof(int); sizeof(a); //where a is an int sizeof(c); //where c is a const //pointers and arrays - pt1 //with pointers: void Sort(int *, const int); ... int main(){ int aSize = 15; int a[aSize]; ... Sort(a, aSize); } ... void Sort(int *ar, const int s){ ... ar[j] = ... ... } //without pointers: void Sort(int [], int); ... int main(){ ... Sort(a, aSize); ... } ... void Sort(int ar[], int s){ ar[4] = ... } //references: int a; int &b = a; a = 3; //and also b b = 5; //and also a //references through functions: int a = 9; int &bad(int); int main(){ int &b = bad(5); //now b==a==14 //bad returns a reference to a, and I put it in b } int &bad(int val){ a+=val;

return a; } //pointer arithmetic vptr = &v[0]; //v is an int array, for example vptr += 3; //moves pointer to v[3]'s address //and similar operations: meaningful only on arrays: //ptr1 - ptr2 = number of places between them... //if (ptr1>ptr2 && ptr3 = NULL)... //pointer assignment: if not same type, a cast is called //pointer to void: void *a; //no cast to convert to void pointer, cannot write: *a = ... //pointers and arrays - pt2 int b[5]; int *bpt; bpt = &b[0]; bpt == b; //name of array is a pointer to first element b[n] = *(bpt + n); //equivalent expressions bpt[3] = b[3]; //equivalent expressions //arrays of pointers (strings...) char *numbers[4] = {"one", "two", "three", "four"}; //array of 4 pointe rs to char, the first char of the four strings, placed elsewhere in memory cout << numbers[2]; //prints 'three' //multi-dimensional arrays as arguments void shuffle(int[][13]); //only first size can be omitted void deal(const int[][13], const char *[], const char *[]); //pointer to function: <type> <name>(arg1, arg2, <type>(*)(type,type,...), arg4...); //prototyp e void sort(int [], const int, bool (*)(int,int)); //function call: int a[12]; sort(a, 12, ascending); //function body void sort(int a[], const int size, bool (*compare)(int,int)){ ... if ((*compare)(a, b-1))... ... ... } //where ascending will be a function that gets two ints and returns a bo ol: "bool ascending(int,int)" and after "bool ascending(int a, int b){return ... ;}" //char, strings and pointers char *s = "1234abcd"; cout << s; char s[] = "1234abcd"; cout << s; //same thing //CSTRING LIBRARY char *strcpy(char *s1, const char *s2); //copy string char *strncpy(char *s1, const char *s2, int n); //copy at most n chars char *strcat(char *s1, const char *s2); //concatenate strings

char *strncat(char *s1, const char *s2, int n); //cat at most n chars to s1 int strcmp(const char *s1, const char *s2); //returns > < = 0 result string comparison (resp. s1 > < = s2) int strncmp(const char *s1, const char *s2, int n); //compares up to n-th char char *strtok(char *s1, const char *s2); //tokenizes: first call, give string s1 and separator(s) s2, urns (pointer to) first token //consecutive calls: give NULL as s1, returns next tokens //when returns NULL, no more tokens int strlen (const char *s); //returns size (not counting terminating ') //STRUCT AND CLASSES //STRUCT //declaration struct <name>{ <type> <name>; <type> <name>; ... }; //example struct person{ int age; char *name; }; ... person mike; mike.age = 12; person *pptr; pptr = &mike; cout << mike.age; cout << pptr->age; //same effect cout << (*pptr).age; //same effect //CLASSES //declaration: example class Time{ public: Time(); //constructor ~Time(); //destructor void funct(int,int); ... private: int a; //not visible from outside int privatefunction(int,int); //internal utility functio n }; ... Time myTime, timearr[4], *timeptr; //instance declaration // timeptr->, myTime.funct(a,b), (*timeptr).funct() etc... like struct's //after class declaration: <type> <classname>::<functio_membername>(arglist){function body} //NO ty pe if CONSTRUCTOR/DESTRUCTOR void Time::function(int a, int b){ ...//from within this I call privatefunction without par ticular syntax of the ret

'\0

... } Time::Time(){...} Time::~Time(){...} //function can be defined within class definition: no prototype, no "cla ssname::" //constructor can take arguments: Time(int = 2, char = 't'); //prototype and defaults Time::Time(int a, int b){ //initial settings } Time myTime(3,'g'); //in main() //references and classes class <...>{ ... int &fname(int); //prototype of a function that returns a reference to an int ... }; //class assignment time t1,t2; ... t1 = t2; //memberwise assignment //classes can be function return type, or function arguments... const Time myTime(12,11); //in class body, as prototype: int A(arglist...) const; //in function definition int A(arglist) const {...} //this forces everything in function to be constant: I do not change eve rything within A //(constructor/destructor cannot be const) //if myTime is const, non-const myTime members cannot be called //const in class class A{ const int a; //without declaring the value int b; } //and then in the costructor A::A(int alpha, int beta) : a(alpha) {b = beta} //if they are objects it is: "a(init1,init2)" //nested classes: constructors within are called before external ones. ( LIFO) //in a string-class constructor len = strlen(lname); len = (len<25 ? len : 24); strncpy (lastname, lname, length); lastname[length] = '\0'; //Friend keyword //friend function: //in the friendship-giving class, prototype:

friend int function(...); //friend class: friend class <name> //this class is granting friendship //if c1 is giving friendship to c2, "friend class c2" in c1's de finition //example with friend function class count { friend void setx(count &, int); public: count(){x=0;} void print()const{cout << x << endl;} private: int x; }; void setx(count &c, int val){c.x=val}//being friend, it can access to pr ivate member x //this: it is a pointer to the current class instance. //in a non-const member it's a <classname> *const //in a const member it's a const <classname> *const //can be returned by a function ... {return this} or {return *this} to r eturn the object instead of a pointer to it //if setHour returns *this, one can implement D.setHour.setMinute.setSec ond: "cascading member function call" //and it will be like: Time &Time::SetHour(...){ ... return *this; } //static keyword (variables, functions (functions: only in prototype)) //shared by all instances of class; exists even if no objects created //static variables: //public: accessible from outside with <classname>::<var_name> //private: accessible from a 'public static' member function //static function: //cannot access to non-static variables and this, can be called from outside: <classname>::<static_public_name>(arguments) //class prototype: class <classname>; //other stuff: example, two classes that are both argument of a friend... class <classname>{ ... }; //NEW AND DELETE //new: allocates memory for object and returns the pointer to it //delete: frees the memory area allocated with 'new'. int a; int *arr = new int[10]; double *thingptr = new double(2.9); Time *timeptr = new Time; a = new int; ...

delete delete delete delete

a; [] arr; thingptr; timeptr;

//OPERATOR OVERLOADING //the function is written as usual, its name is operator<operator symbol > //example: operator++... //already overloaded: = and & //can be overloaded: + - * / % ^ & ~ ! = < > += (and similar) && ++ -- ->* , -> [] () new delete new[] delete[] //cannot be overloaded: . .* :: ?: sizeof //cannot change: precedence, associativity, number of operands //no new operators //cannot overload operators for built-in data types //operator function can be class-member or nonmember //if () [] -> or assignments are overloaded, function must be me mber //member function overloading: //leftmost operand must be class object (use nonmember function otherwise) //nonmember function overloading //must be 'friend' if it has to access private or protected memb ers //allows commutativity //'ostream<< (newclass)" and "istream >> (newclass)" overloading: //operand is type "[i o]stream &" //must be nonmember because left operand is not class member (it is [i o ]stream type) //therefore it must be friend to access class private data: class PN{ friend ostream &operator<< (ostream &, const PN &); public: ... private: ... }; ...//end of class prototype; begin of body: ostream &operator<<(ostream &output, const PN &num){ ...//do what I have to do return output; //to allow cascade such as cout << a << b << c; } //unary operator overloading //if it's member function (no 'friend'), no argument, and must b e in 'public:' label bool operator!() const; //if it's not member function (outside public/private labels), o bject is argument: friend bool operator!(const <classname> &); //and after the prototype, everything follows as usual ( "const <classname> &myClass") //binary operator overloading //non-static function member: one argument (= the other operand)

: class A{ public: const A &operator+= (const A &); ... private: ... }; //in main(): y += z; //means y.operator+=(z) //nonmember function: needs 2 arguments: class A{ friend const A &operator+=(A &, const A &); ... ... }; //place here declaration of &operator+=... //in main(): y += z; //means operator+=(y,z) //type conversion //cast operator: //forces conversion between built-in types //and between user-defined and built-in types //conversion operator must be a non-static member functi on (cannot be external friend) //no need to specify return type //example for class A: A::operator char *() const; //this overloads the cast for the conversion from A to char * A::operator int() const; A::operator <anotherclassname> const; //with casting, often overloading is avoided cout << s; //if it's possible, it is cast to a p rintable object (such as char *...) //Increment and decrement operator (++ --) overloading //prefix (++a, --b): //see standard unary overloading: // d1.operator++() is called //postfix (c++, d--): //an int argument is inserted just to distinguish... // d1.operator++(0) is called //two different "operator++" are defined, one that receives one int argu ment, one that receives nothing: one returns itself, the other returns a non-mod ified copy...

Вам также может понравиться