【问题标题】:How to return a dynamic object from operator function?如何从运算符函数返回动态对象?
【发布时间】: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 &amp; IntegerSet::operator-应该是IntegerSet IntegerSet::operator-
  • @juanchopanza 谢谢你 :)

标签: c++ arrays class dynamic operator-keyword


【解决方案1】:

您必须按价值返回。当函数返回时,本地对象将被销毁,没有办法阻止。

为此,您的班级必须正确遵循Rule of Three 以确保它可以正确复制。在 C++11 或更高版本中,您还可以考虑使其可移动,以避免不必要的内存分配和复制(尽管在这种情况下,无论如何都应该省略复制)。

更好的是,遵循零规则并存储 vector&lt;int&gt;,它将为您完成所有这些工作,而不是试图处理原始指针。

【讨论】:

  • 感谢您的建议,但由于这是我的课程的一个硬件,我只能使用数组而不是任何其他形式的数据容器。
  • @Astronautilus:好的。在这种情况下,请仔细查看您的析构函数、复制构造函数和复制赋值运算符,以确保在复制您的类时它们会做正确的事情。
  • 是的..顺便说一句,如果你能检查我的构造函数、复制构造函数和析构函数,那就太好了。虽然我已经对它们进行了测试并且它们工作正常。
【解决方案2】:

你需要改成按值返回结果。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 2015-12-15
    • 2020-07-20
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多