1. I just learned C++ in my freshman year and encountered some problems. If there is something wrong, I hope you can give me some advice.
2. When instantiating a member function of a class template, why is the destructor automatically called after the function ends? For example
~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];
In this caseint a2[] = { 2,4,1,6,0 };
int a4[] = { 2,4,6,8 ,9 };
set<int> t2(a2, 5);
set<int> t4(a4, 5);
When calling t2.intersection(t4);
, destory!
will be displayed at the end. Why is the destructor called so early? At this time, if delete []p is added to the destructor, an error will be reported@_@
伊谢尔伦2017-05-16 13:27:14
//这里的s2会进行拷贝构造,变成 (set &s2) 就没有事了
void set<T>::intersection(set s2){
//start
//...
//end
} // 这里的s2会调用析构