首页 > 解决方案 > 从对象返回函数c ++返回一个新对象

问题描述

我正在开发一个程序,该程序根据集合论相交由 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();
        }
     }

}

}

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

标签: c++c++11

解决方案


在这个循环中:

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;
}

推荐阅读