在构造函数中确定数组大小[关闭]

问题描述 投票:0回答:1

我试图拥有一个带有数组的类,但我不想在头文件中设置其大小,因为它仅在构造函数期间计算,并且我需要在设置大小后迭代数组。

我可以创建一个指针,然后在构造函数中创建一个新数组,但随后我无法使用基于范围的

for
循环(其他语言中的
for
-
in
循环)迭代该数组。

我收到此错误:

这个基于范围的“for”语句需要一个合适的函数,但没有找到

头文件:

class Map
{
public:
    static const int tileSize = 25;

    Tile* tileSet;

        Map();
}

.cpp 文件:

Map::Map() {

    sf::Texture texture;

    if (texture.loadFromFile("../Assets/Image/BackgroundTileSet.png")) {
        tileSet = new Tile[texture.getSize().x * texture.getSize().y / tileSize];
        
        for (Tile tile : tileSet) {
            tile.texture = &texture;
            tile.sprite.setTexture(*tile.texture);
        };
    }
}

我认为使用传统的基于索引的

for
循环会起作用,但我宁愿使用
for
-
in
。 (“传统”如
for (int a = 0; a < size; a++)
。)

c++
1个回答
1
投票

首先,向

Tile
类添加一个构造函数,该类采用
sf::Texture&
:

Tile(sf::Texture& t)
  : texture(&t), sprite(t) {}

请注意,可能不需要单独存储纹理,因为您可以使用

sprite.getTexture()
来获取它。

然后您可以一次性创建一个包含正确内容的

std::vector<Tile>

class Map {
public:
  Map() {
    if (texture.loadFromFile("../Assets/Image/BackgroundTileSet.png")) {
       ...
    }
    size_t numTiles = texture.getSize().x * texture.getSize().y / tileSize;
    tileSet = vector<Tile>(numTiles, Tile{texture});
 }

private:
  sf::Texture texture; // stored at this level since it must outlive the tile set
  std::vector<Tile> tileSet;
};

使用 std::span 的替代方法

如果您确实想让当前的方法发挥作用,您可以像这样加入

std::span

size_t numTiles = texture.getSize().x * texture.getSize().y / tileSize;
tileSet = new Tile[numTiles];

for (Tile& tile : std::span(tileset, numTiles)) {
  // as before
}
© www.soinside.com 2019 - 2024. All rights reserved.