在 C++ 中,我們用 new 取代了 malloc 的功能:
語法: p_var = new typename;
Typename can be any basic data type or user-defined object (enum, class,and structincluded). If typename is of class type, the default constructor is called to construct the object.
和 malloc 一樣,new 可以創造出系統內建data type 或是使用者自訂 data type 的指標,並且 return 一個指標指向該物件。
和 C 不同的是,我們可以直接使用 new 指定初始值,例如
int* p_scalar = new int(5);
等同於:
int* p;
p = (int*) malloc (sizeof(int)); // 雖然說 C 不用這行也能 work
p = 5;
這個功能配給空間給一維陣列時特別好用
語法: p_var = new type [array_size];
int* p_array = new int[5];
等同於:
int* p_array;
p_array = (int*) malloc (sizeof(int)*array_size); // 顯然 new 簡單多了!
在 C 裡,malloc 之後要 free,相對於 free ,C++ 則是使用 delete:
int *p_var = new int;
int *p_array = new int[50];
delete p_var;
delete [] p_array;
其他:
* new 無法對 array 初始化
* 如果該型別沒有 default constructor,初始化時 complie 會出現錯誤(不會自動給空間)
* 二維以上的陣列在C++通常都會偏好使用 Vector 宣告