c++ - 初始化后的 vector at() 超出范围错误

标签 c++ class inheritance vector

大家好(这里是SO的第一篇文章)。
我正在开发一个基于文本的 C++ 游戏(Ants vs Some Bees)作为一个附带项目,其中我有一个 Insect 指针 vector ,我在一个 init 函数中初始化

void Colony::initBoard()
{
    vector<Insect*> gameBoard (10, nullptr);

    //check to see that vector is properly intialized
    for (auto &it : gameBoard)
    {
        std::cout << it << std:: endl;
    };
    //check the size
    cout << gameBoard.size() << endl;
}

下一个目标是将一些 Ant 放在 vector 中的指定点,我的 Ant 类继承自昆虫类。这是使用 .at() 方法时出现 vector 超出范围错误的地方,并且 vector 显示的大小为零。
void Colony::createAnt()
{   
    int position = 0;
    cout << "Where do you want to set your Ant? " << endl;
    cin >> position;
    //checking for size (0 here for some reason)
    cout << gameBoard.size() << endl;

    ...//validation stuff done here, not relevant to post

    gameBoard.at(position) = new Ant(position);
    isOccupied = true;
}

在 main 中运行此代码时,调用 init 函数时大小为 10,调用 place ant 时大小为 0,我不知道为什么。

到目前为止,我的主要功能只是测试此功能的功能。
    Colony col;
    col.initBoard();
    col.createAnt();
vector<Insect*> gameBoard;是 Colony 类中的私有(private)成员变量。我的想法是该 vector 以某种方式超出了范围,但我不确定如何修复。提前感谢任何提示/建议

最佳答案

initBoard() ,您已经声明了一个名为 gameBoard 的局部变量您正在填写而不是同名的类(class)成员。

更改此行:

vector<Insect*> gameBoard (10, nullptr);

为此:
gameBoard.resize (10, nullptr);

话虽如此,由于您在编译时知道元素的数量,因此请考虑使用固定数组而不是 std::vector ,例如:
std::array<Insect*, 10> gameBoard;

无论哪种方式,您都应该存储 std::unique_ptr<Insect>元素而不是原始 Insect*指针,例如:
gameBoard.at(position).reset(new Ant(position));

或者:
gameBoard.at(position) = std::make_unique<Ant>(position);

关于c++ - 初始化后的 vector at() 超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61860636/

相关文章:

python - 在父类中调用 `super()`

ios - 以非编程方式使用 (UIView) 类 - Swift

objective-c - ObjC 类对象可以符合协议(protocol)吗?

c++ - C++ 中是否有等效的 str_replace?

c++ - 实体组件系统 - 渲染方法

c++ - C++中用户定义类的大小

iOS isKindOfClass 和 isMemberOfClass 之间的区别

java - 使用 Jackson 组合而不是继承

c++ - C/C++ 编译器中的内存泄漏检测

c++ - 为什么当我们打印指向字符类型的指针时,C++ 会显示字符?