當實現一個類有一個內部對象:(Re)的分配給一個2維的std ::向量<bool>私有成員函數內
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++-3.8 main.cpp -std=c++14
我們可以看到你的'object'類和調用(你正在分配新值的位置)嗎?也許有什麼需要設置爲「公共」?如果你認爲問題在於選擇'auto',那麼將它改爲基本的'int'並嘗試。 –
另外,成員函數是否是'const'? –
基本上,你需要創建一個[mcve] –