C++ Memory Management and Array Declarations in Class

具有單一參數的建構是預設,可用來作為隱性轉型用

   IntArray a=10 -> IntArray a =IntArray(10)

要想避免單一參數的建構式自動作為隱性轉型(implicit)用的話,要在建構式前面加explicit修飾字。

   explicit IntArray(n)

2.動態配置 – 正常來說

  1. 創立建構子
  2. 建立記憶體
  3. 釋放記憶體
  4. 解構建構子

在C語言新增叫malloc, 釋放叫free();

C++裡新增稱new,釋放叫delete

Ex:

class Grade{
public:
explicit Grade(int n){
data_ = new int[n]; //未賦值
}
~Grade(){
delete[] data;
}
private:
int *data_;
}
int main(){
IntArray(5);
}

Related codes from my GitHub:
dataStructure/array_3.cpp

發表留言

透過 WordPress.com 建置的網站.

向上 ↑

Yosing'sDailyPractice

是練習,也是實踐

portran

Explore the life truth and beauty

使用 WordPress.com 設計專業網站
立即開始使用