1

## 問c++相關問題

https://ideone.com/e0fFAE

CHuman ，CEmployee解構式如果要delete[] 就會讓資料消失了！可是觀念上new 跟delete要成對才對，還是我應該怎麼正確地去delete呢

### 4 個回答

1

iT邦大神 1 級 ‧ 2020-05-01 10:15:01

Vector

C/C++ array’s size do not change dynamically

(為了加/減一個 element，要整個陣列複製來複製去的)

1

iT邦研究生 2 級 ‧ 2020-05-01 15:08:04

### 關於動態空間的寫法

``````//====資料====
SomeType(某資料型態) *p;
int capacity; //容量
int index; //寫入到哪邊，0<=index<capacity

//===建構===
p=new SomeType(基礎長度)
capacity=基礎長度
index=0

//===寫入===
if(index+寫入的長度>=capacity) {
擴充容量(並更新capacity)
}

``````

PS. 擴充容量的方式有很多種，常見的方式是每次容量乘以2

0
wwx
iT邦好手 1 級 ‧ 2020-05-02 16:05:19

mName = NULL;

if (mName) delete[] mName;

if (mName) delete[] mName;

0
kphuang
iT邦見習生 ‧ 2020-05-03 05:46:03

### 先寫出正確的程式碼

``````NewEmployees[index] = mEmployees[count];
``````

``````NewEmployees[index] = mEmployees[index];
``````

### delete[] mName; 是必須嗎？

``````cout << "debug 2\n";
delete[] mName;
...
cout << "debug 1\n";
delete[] mEmployees;
``````

``````debug 1
debug 2
debug 2
``````

"debug 2"跑了兩次，可見delete[] mEmployees;也會跑CHuman的解構子亦即delete[] mName;

### 先寫程式碼驗證

``````mEmployees = new CEmployee[count+1];//請問這行可以省略嗎

``````

``````void List() {
CEmployee * e = NULL;
for (int i = 0; i < count; ++i)
{
e = &mEmployees[i];
cout << "ID:  " << (*e).GetId() << "\n"
<< "姓名: " << (*e).GetName() << "\n"
<< "年齡: " << (*e).GetAge() << "\n";

}
}
``````

``````...
cout<<"Finish !\n";
Employees.List();
...
``````

### 用什麼資料型態或結構去描述系統

``````class CEmployees {
private:
CEmployee mEmployees[100];
int count;
...
}
``````

``````class CEmployees {
private:
vector<CEmployee> mEmployees;
int count;
...
}
``````