改变数组中的对象,但不改变对象的数量- c++
changing the objects in an array but not the number of objects - c++
我正在努力在我的程序中的某个地方分割错误,我认为它可能是在这段代码。ingredients
是指向Ingredient
对象数组的指针。现在,重载的*操作符只更改数组中的每个Ingredient对象。所以,在我看来,我只是改变了指针指向的对象,但我没有改变数组的大小,也就是说,我没有试图向Ingredient
数组添加更多的对象。出于某种原因,我是否仍然需要释放内存?
Recipe Recipe::operator*(const Fraction multiplier)
{
for (int count = 0; count < numIngredients; count++)
{
ingredients[count] * multiplier;
}
servings = multiplier;
return *this;
}
首先,一些评论
你的Recipe::operator*
不是const
,当它应该是,并修改自己。
这就像这样做:
a = 5
b = a * 2
和a = 10
在这个结尾。
这在概念上是错误的。
你所做的是定义的Recipe::operator*=
您应该像下面这样定义Recipe::operator*=
和Recipe::operator*
:
Recipe& Recipe::operator*=(const Fraction multiplier)
{
for (int count = 0; count < numIngredients; count++)
{
ingredients[count] * multiplier;
}
servings = multiplier;
return *this;
}
Recipe Recipe::operator*(const Fraction multiplier)
{
Recipe x = *this;
x *= multiplier;
return x;
}
关于段错误,我们需要查看所有的代码来查看那里发生了什么。它可以在程序中的任何地方,但要注意的是你的复制构造函数。
我在代码中没有看到任何必然导致崩溃的东西,但是其他地方的问题可能导致它在那里崩溃。例如,如果numIngredients成员不正确,或者成分指针为空。奇怪的是,操作员*被用于配料。通常,二元操作符*会返回一个值而不修改参数,但是没有使用返回值。可以定义Ingredient::operator*以某种方式修改成分,但这是不寻常的。为了使问题变得清晰,您可能需要提供更多的代码。
查看"numIngredients
"的值。
相关文章:
- 如何访问和改变存储在矢量C++中的对象
- 通过从构造函数中的'this'复制的指针改变常量对象
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 使用(非对象)API 时改变表数组C++而不重新创建整个平面缓冲区
- 为什么我的函数不改变对象的属性
- 改变对象的原点点使其以不同的轴移动
- 更改指针指向的对象,但对象不会改变
- 对列表中的每个对象调用成员函数,以改变对象所在的列表
- 当函数应该改变对象的状态时,是选择成员函数还是朋友函数
- 一个什么都不做的函数可以改变一个对象吗?
- 改变一个已经压入的列表(在vector对象上)会改变vector对象上的列表吗?
- 如何改变一个c++对象的类(实现可变类型)
- 如果一个引用一旦被初始化为一个对象,它就不能被改变,为什么这样做呢?
- 在c++中,改变指针返回后指向的对象
- 改变数组中的对象,但不改变对象的数量- c++
- 将字符串保存到重载括号中,不改变对象的字段
- 如何用静态方法改变c++中对象的属性
- 为什么每次我试图改变对象时,我的复制构造函数都会产生段错误?
- 改变对象
- 当调用改变它的成员函数时,不改变C对象成员