读书人

C++集合的交、并集出错了看一哈

发布时间: 2012-04-11 17:42:33 作者: rapoo

C++集合的交、并集,出错了,大虾看一哈
下面的这个程序是求两个集合的交集、并集、差,但是程序显示不正确,求大仙指路!
#include<iostream.h>
class Set
{
int *p;
int count;
public:
Set();
Set(int[] ,int);
int find(int);
Set operator+(const Set &);
Set operator-(const Set &);
Set operator*(const Set &);
void disp();
};
Set::Set()
{
p=NULL;
count=0;
}
Set::Set(int s[],int n)
{
p=s;
count=n;
}
int Set::find(int x)
{
int i=0;
while(i<count)
{
if(p[i]==x)
return 1;
i++;
}
return 0;
}
Set Set::operator+(const Set &s)
{
int b[100];
for(int i=0;i<count;i++)
b[i]=p[i];
for(int j=0;j<s.count;j++)
if(find(s.p[j])==0)
{
b[i]=s.p[j];
i++;
}
return Set(b,i);
}
Set Set::operator*(const Set &s)
{
int b[100],j=0;
for(int i=0;i<count;i++)
if(find(s.p[i])==1)
{
b[j]=s.p[i];
j++;
}
return Set(b,j);
}
Set Set::operator-(const Set &s)
{
int b[100],j,i=0;
for(j=0;j<count;j++)
if(find(s.p[j])==0)
{
b[i]=p[j];
i++;
}
return Set(b,j);
}
void Set::disp()
{
for(int i=0;i<count;i++)
cout<<p[i]<<" ";
cout<<endl;
}

void main()
{
int a[]={4,56,8,89};
int b[]={4,688,8};
Set A(a,sizeof(a)/sizeof(a[0])),B(b,sizeof(b)/sizeof(b[0])),C;
cout<<"A:"<<endl;
A.disp();
cout<<"B:"<<endl;
B.disp();

C=A+B;
cout<<"A+B:"<<endl;
C.disp();

C=A-B;
cout<<"A-B:"<<endl;
C.disp();

C=A*B;
cout<<"A*B:"<<endl;
C.disp();
}


[解决办法]
Set Set::operator+(const Set &s)
{
int b[100];

return Set(b,j);

}

Set Set::operator*(const Set &s)
{
int b[100],j=0;
return Set(b,j);

}

Set Set::operator-(const Set &s)
{
int b[100],j=0;
return Set(b,j);

}
在上面的三个重载运算操作符的函数中,都定义了临时数组b[100],而且最后也返回了b,当这三个函数调用结束后,临时数组所占的内存会被释放,所占的内存有可能被重用也有可能还没被重用,结果不确定

读书人网 >C++

热点推荐