从对象返回函数C ++返回新对象

时间:2019-09-08 19:15:07

标签: c++ c++11

我正在研究一个根据集合论相交的程序,该集合由2个对象表示。每个对象可以包含0个或多个元素。 该函数是给定的,只能在内部执行才能更改。

在我的代码中,我检查调用对象和第二个对象(otherIntSet)是否为空,如果是,则它们在空集处相交。 如果它们包含任何元素,我将检查data []中的元素是否包含在otherIntSet中。我使用“返回IntSet();”但我得到的只是空集。

IntSet IntSet::intersect(const IntSet& otherIntSet) const
{
  if ( (this->isEmpty() ) && (otherIntSet.isEmpty() ) )
   {

    return IntSet(); 
   }
  else 
  {
    for (int i = 0; i < used; ++i)
    {
        if (otherIntSet.contains(data[i]) )
        {
            IntSet().add(data[i]);
            cout << IntSet();
        }
     }

}

}

我不确定如何返回正确创建的新对象,以便实际保存添加到该对象的元素。 谢谢

1 个答案:

答案 0 :(得分:5)

在此循环中:

for (int i = 0; i < used; ++i)
{
    if (otherIntSet.contains(data[i]) )
    {
        IntSet().add(data[i]);
        cout << IntSet();
    }
 }

您在每次迭代中创建一个临时IntSet对象,那又是什么呢?消失吗?那有什么意义呢?相反,您想要的是一个对象,将其填充并返回:

IntSet result;
for (int i = 0; i < used; ++i)
{
    if (otherIntSet.contains(data[i]) )
    {
        result.add(data[i]);
    }
}
return result;

顺便说一句,您的第一个条件应该是“或”,这比“和”更好(更广泛):

if ( (this->isEmpty() ) || (otherIntSet.isEmpty() ) )

您可以玩,甚至最终得到这样的东西:

IntSet IntSet::intersect(const IntSet& otherIntSet) const
{
    IntSet result;
    if (!otherIntSet.isEmpty())  // <-- note negation
    {
        // We don't need to check if this->isEmpty(), the loop
        // won't loop anyway if it is. And in case it isn't
        // it saves us unnecessary call. Assuming that "isEmpty()"
        // is derived from "used".
        for (int i = 0; i < used; ++i)
        {
            if (otherIntSet.contains(data[i]) )
            {
                result.add(data[i]);
            }
        }
    }
    return result;
}