如何从运算符函数返回动态对象
How to return a dynamic object from operator function?
我正在为编写一个运算符函数,其中我的类对象是一个动态整数数组。运算符接受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会更有意义。
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 动态数组传递给 main 中用随机值填充的函数,返回值3221226356
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- 静态分配和动态分配返回不同的答案
- 动态调用具有不同返回类型的相同命名函数
- 在存储库中,筛选器函数返回动态向量或其他存储库
- C++返回数组而不进行动态内存分配?
- C++ 返回具有最小硬币的数组/向量以获得价值动态规划
- C++ 如何从函数返回动态分配的数组
- 动态指针引用数组由三元运算符返回值,但有异常
- 动态使用返回的数组,如何释放其内存
- 如何让C++课"return"有能力?(或用户定义类型的返回动态)
- 如何从操作员函数返回动态对象
- 如何在没有指针的情况下返回动态结构
- 从函数返回动态数组后将其删除
- 无法从函数返回动态字符串
- 如何返回动态分配的数组
- 如何从运算符函数返回动态对象