1.大一剛學C++,遇到了點問題,如有不妥的地方還望指教。
2.實例化類別模板的成員函數,函數結束後為什麼會自動呼叫析構函數? 例如
~set()
{
cout<<"destory!"<<endl;
}
private:
int size;
T *p;
void set<T>::intersection(set s2) //交集
int cnt = 0;
int size2 = s2.size;
sort(p, p + size);
sort(s2.p, s2.p + size2);
int MaxSize = max(size, size2);
T *tmp = new T[MaxSize];
if (MaxSize == size)//集合A含元素个数大于B
for (int i = 0; i<MaxSize; i++)
if (s2.b_search(p[i])) //二分查找
tmp[cnt++] = p[i];
else if (size != size2)
for (int i = 0; i<MaxSize; i++)
if (b_search(s2.p[i]))
tmp[cnt++] = s2.p[i];
for (int i = 0; i<cnt - 1; i++)
cout << tmp[i] << ",";
cout << tmp[cnt - 1];
這樣的話int a2[] = { 2,4,1,6,0 };
int a4[] = { 2,4,6,8 ,9 };
set<int> t2(a2, 5);
set<int> t4(a4, 5);
#呼叫t2.intersection(t4);
時最後會顯示destory!
為什麼析構函式呼叫的那麼早?此時如果在析構函數中加上delete []p 還會報錯@_@
雷雷