繁体   English   中英

为什么我不能更改向量中的对象?

[英]Why can't I change objects in a vector?

我有一个TileGrid类,它包含一个std::vector< std::vector<Tile> > 访问向量中的Tile对象有效,但我无法更改其属性? 为了完成,这里是所有相关的类:

tilegrid.h

#include <vector>
#include "tile.h"

class TileGrid {

public:
  TileGrid();
  TileGrid(unsigned int rows, unsigned int cols);
  virtual ~TileGrid();
  unsigned int getRows() const { return rows_; };
  unsigned int getCols() const { return cols_; };
  Tile atIndex(unsigned int row, unsigned int col) const { return tiles_[row].at(col); };

private:
  std::vector< std::vector<Tile> > tiles_;
  unsigned int rows_;
  unsigned int cols_;

};

tilegrid.cpp

#include "tilegrid.h"

TileGrid::TileGrid() : rows_(0), cols_(0) {
}

TileGrid::TileGrid(unsigned int rows, unsigned int cols) : rows_(rows), cols_(cols) {
  tiles_.clear();
  for (unsigned int y = 0; y < rows_; y++) {
    std::vector<Tile> horizontalTiles;
    for (unsigned int x = 0; x < cols_; x++) {
      horizontalTiles.push_back(Tile());
    }
    tiles_.push_back(horizontalTiles);
  }
}

TileGrid::~TileGrid() {
}

tile.h

class Tile {

public:
  Tile();
  virtual ~Tile();
  bool isActive() const { return isActive_; };
  void setActive(bool status) { isActive_ = status; };

private:
  bool isActive_;

};

tile.cpp

#include "tile.h"

Tile::Tile() : isActive_(false) {
}

Tile::~Tile() {
}

main.cpp中

#include "tilegrid.h"
#include <iostream>

int main() {

  TileGrid tg(20, 20);

  for (unsigned int i = 0; i < tg.getRows(); i++) {
    for (unsigned int j = 0; j < tg.getCols(); j++) {
      if (tg.atIndex(i, j).isActive()) {
        std::cout << i << "," << j << " is active" << std::endl;
      } else {
        std::cout << i << "," << j << " is NOT active" << std::endl;
      }
    }
  }

  // This is all working. But when I for example use the setActive function, nothing changes:

  tg.atIndex(1, 0).setActive(true);

  // When I print it again, the values are still the ones that were set in the constructor

  for (unsigned int i = 0; i < tg.getRows(); i++) {
    for (unsigned int j = 0; j < tg.getCols(); j++) {
      if (tg.atIndex(i, j).isActive()) {
        std::cout << i << "," << j << " is active" << std::endl;
      } else {
        std::cout << i << "," << j << " is NOT active" << std::endl;
      }
    }
  }

  return 0;

}

我真的很抱歉所有这些代码......我尽量保持它尽可能短,但我认为最好发布它!

所以是的,我的问题是setActive函数。 当我只是创建一个Tile并调用它的setActive函数时,一切正常,但是当我通过TileGrid对象调用它时,它不会。

我已经试着自己解决这个问题几个小时了,我不能再思考了。 我真的很绝望,你能看看,也许帮助我吗?

在你的方法中:

Tile atIndex(unsigned int row, unsigned int col) const

你应该返回对Tile的引用:

Tile& atIndex(unsigned int row, unsigned int col)

现在你正在返回副本,这就是为什么修改不起作用的原因。 它也不应该是const ,否则会出现编译错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM