c++ - 只读变量不可赋值

标签 c++

是的,这是作业,我的代码要求我输入一个数组,该数组在输入数字 0 或达到最大整数数 ARRAY_SIZE 时终止,所以当我输入我的代码行 array[num_elements]=i; 返回一个错误,指出 Read-only variable is not assignable

void read_list(const int array[], int & num_elements) {
    int i(1);

    cout<<"Enter list of "<< ARRAY_SIZE<<" integers (ending with 0)";

    while (i != 0 && num_elements < ARRAY_SIZE) {
        cin >> i;
        array[num_elements] = i;
num_elements++;
    }

}

最佳答案

好吧,你的数组字段是只读变量,所以你不能给它们赋值。

删除 const 限定符,它应该可以正常工作。

不过,我不确定 array[num_elements] = num_elements++ 是否有用。 也许您想改为 array[num_elements++] = i

关于c++ - 只读变量不可赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22788927/

相关文章:

c++ - Windows 管道到 C++ 程序

c++ - FindFirstFile 在根路径上失败

c++ - const 函数可以在 C++ 中递归,只要它修改可变变量吗?

c++ - 我可以从这个矩阵算法中得到旋转吗

c++ - 使用 'assert' 验证参数数量

c++ - 从模板函数中取消引用的迭代器推断类型

c++ - C++ 中的 constexpr 是什么?

c++ - MS STL 库是否包含内存泄漏?

c++ - 在函数 C++ 中使用多个结构

c++ - C++ 中的长手乘法