Skip to content

C++

Reference

C++ Primer Plus, sixth edition, Stephen Prata.

Elementary

Class & Object

Inheritance

Dynamic Memory Allocation

Exception

Streams

Appendix | 附录

Template | 元代码

Reuse source code. It generates code for compiling.

  • Generic programming(泛型, universal type)vs 范形 model shape. Use type as parameters in class or function definitions.

Function Template | 函数模板

C++
void myswap(int &x, int &y) // only calls when passing in "int"
{
  int temp = x;
  x = y;
  y = temp;
}

// T is tyep parameter class
template <class T>
void myswap(T &x, T&y)
{
  T temp = x;
  x = y;
  y = temp;
}

int main()
{
  int a=6,a=5;
  double c=1,d=2;
  myswap(a.b); // right
  myswap(a,c); // error, parameters a,c must be the same type
}

// but if we do this
template <class T1,class T2>
void myswap(T1 &x, T2&y)
{
  T1 temp = x;
  x = y;
  y = temp;
}

compiler need to know the type T if we do not explicitly give varible of type.

C++
template<class T>
void f()
{
  T a;
}

int main()
{
  f<double>();
}

Class Template | 类模板

A class declaration.

All the functions in the template are function template.

C++
template <class T>
class vector{
  public:
  vector(int s)size(s){}
  T& operator[](int s);
};

// definition
template <class T>
T& vector<T>::operator[](int s){
  return 0;
}

Template nest:

```c++
vector< vector<double*> >

Template arguments can be constant expresstions, Non-type parameters with a default argument.

C++
template<class T, int bounds=100>
class FixedVector{
public:
  FixedVector();
  T & operator[](int);
private:
  T elements[bounds]; 
};

template<class T, int bounds=100>
T & FixedVector<T, bounds>::operator[](int i){
  return elements[i];
}

int main()
{
  FixedVector<int, 10> v1;
  FixedVector<int> v2; // use default parameter 100

}

All the content of template should be put in .h file for they are only declarations. Remember we also have to put inline function and static member variables in .h file.

STL(standard template library)

All the following identifiers in library are in std namespace.

This is also called Container(lowercase).

  • Sequential

Sequential classes

  • vector(variable array)

It is easy to use index to search and save memory

C++
vector<typeName> vt(n_ele);
vector<int> x;
x.push_back(1);

reload p++

C++
vector<int>::iterator p;
for(p=x.begin(); p<x.end(); p++)
  cout << *p <<  ;
or
C++
for(auto k: x)
cout << k <<  ;

auto means the compiler can identify the type of the variable itself.

for 仅用于遍历全部(range-based for loops)

放进容器里的内容是clone

直接使用下标,不使用push_back/pop 是不会改变size的。

C++
x[999] = 9; // no error but invalid
  • array

  • fixed length, use stack.

C++
array<typeName, n_ele> arr;
n_ele should be constant

  • list(double-linked-list) It can insert/delete items very quickly.

C++
list<int> L;
list<int>::iterator li;
li = L.begin();
L.erase();
++li; //wrong! li has been removed.
right:

C++
li = L.erase(li)
li now points to nest node
  • others

Deque(double ended queue), forward_list, maps(HashMap)

C++
map<string, float> price;
price[snapple] =0.75

Cast Operators

  • static_cast

It is used in basic type/class conversion, (void *) to goal type pointer conversion, child to parent conversion. And it takes place in compiling.

C++
int main(){
  int a=10;
  double b = static_cast<double>(a); // int to double

  class Base {};
  class Derived: public Base {};
  Derived d;
  Base* basePtr = static_cast<Base*>(&d); // child to parent

  void* voidPtr = &a;
  int* intPtr = static_cast<int *>(voidPtr); // void * to int *
}
  • dynamic_cast

usually used in down cast(see parent as child) in polymorphism.

C++
class Base {
  virtual void foo{}
};
class Derived : public Base {
};

int main(){
  Base* basePtr = new Derived();
  Derived * derivedPtr = dynamic_cast<Derived*>(basePtr); // check when running program, better for locate error
  if(derivedPtr){
    cout << "cast succeed.\n";
  }else{
    cout<< "cast failed.\n";
  }
  delete basePtr;
}
  • const_cast

volatile means the variable is changable and should not be optimized by compiler.

const_cast remove a const variable into non-const.

C++
int main(){
  const int a=10;
  int * b = const_cast<int *>(&a); // remove const 
  *b = 20; 
}
  • reinterpret_cast

used in low class conversion, which is dangerous.

C++
int main(){
  int a=65;
  char* chPtr = reinterpret_cast<char*> (&a);
  cout<< *chPtr << endl; // output 'A', whose ASCII is 65.
}