改变数组中的对象,但不改变对象的数量- c++

changing the objects in an array but not the number of objects - c++

本文关键字:改变 对象 c++ 数组      更新时间:2023-10-16

我正在努力在我的程序中的某个地方分割错误,我认为它可能是在这段代码。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"的值。