返回语句打破我的功能C

Return statement breaking my function c++

本文关键字:功能 我的 语句 返回      更新时间:2023-10-16

,所以我在main中调用一个函数: B.remove()

来这里 m_arrays[m_oldest]->remove()

然后最后在这里:

int MyClass::remove() {
    cout << "this is the remove function"<< endl;  //debugging line
    int lastVal = 0;
    for (int i = start; i < capacity; i++) {  //actual remove function
        if (m_array[i] != NULL) {
            int lastVal = m_array[i];
            m_array[i] = NULL;                  // sets to null
            m_size--;                           //increment
            break;
        }
    }
    m_start++;                                  //increment
    return lastVal;
}

如果我删除包含LASTVAL的代码,则该函数正常工作。为什么是这样?有什么简单的解决方法吗?如您所见,我试图在从数组中删除值之前返回值。我知道我应该使用向量或其他标准方法,但我不能。我在教科书中看了看,但找不到想要的东西。任何帮助都非常感谢。

您的代码中有两个int lastVal语句 - 一个在for循环之前,其中一个是一个。尝试删除for循环内的声明(并将其设置为分配lastVal = m_array[i];),看看它是否有效。