【发布时间】:2014-06-05 11:50:26
【问题描述】:
我正在编写一个运算符函数 - 我的类对象是一个动态整数数组。 运算符获取 lhs 和 rhs 对象并返回一个对象,该对象是 lhs 中的元素集合,而不是 rhs 中的元素集。
虽然我已经编写了函数,但是我无法返回集合,因为在对象返回后立即调用了析构函数。
IntegerSet & IntegerSet::operator - (IntegerSet & rhs) const
{
IntegerSet temp(capacity);//local object created to store the elements same size as lhs
int k=0;
int lhssize = ElementSize();//no. of elements in the set
int rhssize = rhs.ElementSize();
for (int i=0;i<lhssize;i++)
{
for (int j=0;j<rhssize;j++)
{
if (rhs.ptr[j]!=ptr[i])
{
k++;
}
}
if(k==rhssize)
{
temp = temp + ptr[i];
}
k=0;
}
return temp;
}
如果你看不懂对象,这里是构造函数
IntegerSet::IntegerSet(const int & size)//works correctly
{
capacity = size;
ptr = new int [capacity]();
}
IntegerSet::IntegerSet(const int & size)//works correctly
{
capacity = size;
ptr = new int [capacity]();
}
IntegerSet::IntegerSet(const IntegerSet & copy) : capacity(copy.capacity)//works correctly
{
ptr = copy.clonemaker();
}
IntegerSet::~IntegerSet()
{
capacity = 0;
delete [] ptr;
}
int * IntegerSet::clonemaker() const // works correctly
{
if(ptr==NULL)
{
return NULL;
}
int *tempptr = new int [capacity];
for(int i=0;i<capacity;i++)
{
tempptr[i]=ptr[i];
}
return tempptr;
}
【问题讨论】:
-
二元算术运算符应该返回值,而不是引用。
-
不要引用返回,即
IntegerSet & IntegerSet::operator-应该是IntegerSet IntegerSet::operator- -
-
@juanchopanza 谢谢你 :)
标签: c++ arrays class dynamic operator-keyword