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 还会报错@_@