2014-01-15 116 views
1

我有一个类TileGrid持有​​。访问向量中的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对象调用它时,它不会。

我试图解决这个问题,我自己几个小时,我不能再想直了。我真的很绝望,你可以看看,也许帮助我吗?

回答

9

在你的方法:

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

您应该返回到瓦片的参考:

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

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

+0

你可能需要一个const和一个非const的。 const一个返回一个const引用。 – Roddy

+0

同意,在某些情况下,你可能需要const版本,'const Tile&atIndex(unsigned int row,unsigned int col)const'。 – marcinj

+0

噢我的,非常感谢你<3我试图使用引用,但这个愚蠢的const总是给出一个神秘的编译器错误,我不知道该怎么改变。我现在感到有些尴尬:/ –

相关问题