ESSENTIAL C++
chapter 2
1,final implement of fib_elem()
bool fibon_elem(int pos, int &elem){ if(pos<=0||pos >=1024)//......................... elem=1; int n1=1,n2=1; for(int ix=3;ix<=pos;ix++) { elem=n1+n2; n2=n1; n1=elem; } return true;}
2, passing by value:(make a copy) OR passing by reference:(passing the address)
example : swap(int a, int b) OR swap(int &a, int &b)
3,passing a pointer OR passing a reference parameter
passing a pointer: before we dereference a pointer, we must always make sure it is NOT 0;
4, dynamic memory management
int *p;p=new int(100); // set an initial value
delete p;
int *pia=new int[24]; // allocate an array of heap elements ; means int[24] pia;
delete[] pia;
5, reference to an object
int ival=12;
int &rval=ival;
reference can not be re-assigned to other object
6,providing a default parameter value
void bubble_sort(vector &vec., ofstream *ofil=0){} //set pointer ofil to 0
unlike pointer, reference can not be set to 0
7,
void display (const vector &vec, ostream &os=cout){}
2 RULES about providing default parameter:
1, default values are resolved beginning with right most parameter ,if a parameter is provided a default value,all the parameter to its right must have a default
2, the default value can be specified only once
we can specify the default value in header files
8, local static object
const vector * fibon_seq(int size){static vector elems; //elems is local static object, elems is no longer //destroyed or re-created each invocations of fibonelems.push_back(1);return &elems;}
9, Inline function
inline bool fub(){}
10, overloaded function :(function must be unique)
11, template function
template<typename elemType>
vector<elemType> a;
12; Pointer to function
bool seq_elem(int pos, int &elem, const vector * (*seq_ptr)(int)) //to recognize seq_ptr as a pointer{ const vector *p=seq_ptr(pos); //invoke the function
elem=(*p)[1]; }//you can also you a array to store function pointerconst vector * fib(int size);const vector * (*seq_array[])(int)={fib, .......};seq_ptr=seq_array[1];
13, header file
if the header file is in the same directory as the program text file, we use " "
else we use <>
//header file called num.h//place in it some declaration const vector * fib(int size);// elem=(*fib)[1]extern const vector * (*seq[2])(int); // extern turn the definition to //declaration