(再)赋值给<bool>私有成员函数中的二维 std::vector
(Re)Assignment to a 2 dimensional std::vector<bool> within a private member function
实现类时有一个内部对象:
std::vector<std::vector<bool>> a;
该类使用operator[]
初始化该对象以分配false
:
for(auto i = 0; i < limit; ++i) {
for(auto j = 0; j < limit; ++j) {
a[i][j] = false;
}
}
在私有成员函数中,我们更新此对象以反映当前状态,请注意,object.x
和object.y
是类型int
,new_x
和new_y
:也是
a[object.x][object.y] = false;
a[new_x][new_y] = true;
正在使用的对象类是:
class object {
public:
object(): x(0), y(0) { }
int x;
int y;
};
为什么编译器允许初始化,但却说:
error: expression is not assignable
当我在私有成员函数中重新分配向量中的位时?
这里有一个最小的完全可验证的例子:
Object.hpp:
#ifndef OBJECT_HPP
#define OBJECT_HPP
class Object {
public:
Object(): x(0), y(0) {}
Object(int x, int y) : x(x), y(y) {}
int x;
int y;
};
#endif`
main.cpp
#include "Object.hpp"
#include <vector>
class Function {
public:
Function() : a(10, std::vector<bool>(10)) { }
void moveObjects() {
for(int i = 0; i < 10; ++i) {
editObjects(i,i);
}
}
private:
void editObjects(int new_x, int new_y) const {
a[new_x][new_y] = true;
}
std::vector<std::vector<bool>> a;
};
int main() {
Function f;
f.moveObjects();
}
使用clang编译收到错误:
clang++-3.8 main.cpp -std=c++14
您有:
void editObjects(int new_x, int new_y) const {
a[new_x][new_y] = true;
}
这是不正确的,因为您现在可以在const
成员函数中修改a
。从函数中删除const
限定符。
void editObjects(int new_x, int new_y) {
a[new_x][new_y] = true;
}
问题是私有成员函数定义为const
将对象更改为mutable
解决了问题:
mutable std::vector<std::vector<bool>> a;
相关文章:
- 将二维矢量传递给类
- 将值从二维数组输出到文本文件
- 我在二维向量中是否正确分配了内存
- 带结构的二维矢量:如何存储元素
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- C++ 中动态二维数组的访问冲突
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何将整数字符串转换为整数的二维向量?
- 二维矢量数据成员
- std::vector::clear()ing 二维向量线程的内部向量安全吗?
- 将表示二维数组的 std::vector<std::vector <double> >转换为 cv::Mat
- (再)赋值给<bool>私有成员函数中的二维 std::vector