再學C++

前言

修了電機的資料結構,還蠻有趣的。這篇大概就是放一些容易搞錯的東西。

內容幾乎都來自Data Structure and Programming Prof. Chung-Yang (Ric) Huang。

主文

pointer

The memory size of a memory address depends on the machine architecture

  • 32-bit machine: 4 Bytes
  • 64-bit machine: 8 Bytes

The memory content of the pointer variables

  • For 32-bit machine, the last 2 bits are 0’s
  • For 64-bit machine, the last 3 bits are 0’s

size_t的長度會等於該architecture的pointer的長度

Default Argument

Parameters with default assignments function with default arguments

  • Can only appear towards the end of parameter list
  • Given a function, its default argument can only be defined ONCE

const

const int and int const are the same
const int * and int * const are different !!
Rule of thumb: Read from right to left

  1. f(int*const p): Constant pointer to an integer
  2. f(const int* p) f(int const * p): Pointer to a constant integer
  3. f(const int*& p): Reference to a pointer of a constant int
  4. f(const int*const& p): Reference to a constant pointer address, which points to a constant integer
  5. const A& B::blah (const C& c) const {...}: first: Return a reference to a constant object. second: Passed in a reference to a constant object ‘c’. third: This is a constant method, meaning this object is treated as a constant during this function
void MyClass::f() const {
    _data->g(); //“g()” must be a constant method too!!
}

However, sometimes we MUST modify the data member in a const method

void MyClass::f() const
{
    _flags |= 0x1; // setting a bit of the _flags
}

In such case, declare “_flag” with “mutable” mutable unsigned _flag;

const_cast

explicit

virtual void vf() = 0 means pure virtual

#include

You should create multiple files for different class definitions

  • .h (header) files
    class declaration/definition, function prototype
  • .cpp (source) files
    class and function implementation
  • Makefiles
    scripts to build the project

Leave a Reply

Your email address will not be published. Required fields are marked *