如何从运算符函数返回动态对象

How to return a dynamic object from operator function?

本文关键字:返回 动态 对象 函数 运算符      更新时间:2023-10-16

我正在为编写一个运算符函数,其中我的类对象是一个动态整数数组。运算符接受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;
}

您必须按值返回。当函数返回时,本地对象将被销毁,并且没有办法阻止这种情况的发生。

要做到这一点,你的课必须正确地遵循三条规则,以确保它是正确的可复制性。在C++11或更高版本中,您还可以考虑使其可移动,以避免不必要的内存分配和复制(尽管在这种情况下,无论如何都应该取消复制)。

更好的是,遵循零规则并存储一个vector<int>,它将为您完成所有这些,而不是试图篡改原始指针。

您需要更改以按值返回结果。

IntegerSet IntegerSet::operator - (IntegerSet & rhs) const

此外,当再次查看时,通过const引用提供rhs会更有意义。