(再)赋值给<bool>私有成员函数中的二维 std::vector

(Re)Assignment to a 2 dimensional std::vector<bool> within a private member function

本文关键字:二维 vector std 函数 赋值 lt bool gt 成员      更新时间:2023-10-16

实现类时有一个内部对象:

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.xobject.y是类型intnew_xnew_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;