[英]Returning a new object from a object returning function 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();
}
}
}
}
我不確定如何返回正確創建的新對象,以便實際保存添加到該對象的元素。 謝謝
在此循環中:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.