【发布时间】:2020-09-03 17:20:51
【问题描述】:
大家好(第一次发帖到这里)。 我正在开发一个基于文本的 C++ 游戏(Ants vs Some Bees)作为一个附带项目,其中我有一个 Insect 指针向量,我在 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;
}
下一个目标是将一些蚂蚁放置在向量中的指定点上,我的蚂蚁类继承自昆虫类。这是我在使用 .at() 方法时遇到向量超出范围错误的地方,并且向量显示的大小为零。
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 类中的私有成员变量。我的想法是该向量不知何故超出了范围,但我不确定如何修复。提前感谢任何提示/建议
【问题讨论】:
-
gameBoard 是函数 initBoard 的一个局部变量,它隐藏了同名的成员变量(你说的那个)。这就是您应该提供minimal reproducible example 的原因。
-
谢谢,出于某种原因,我在 init 函数中创建了一个新向量。在构造函数中正确初始化后,我能够让它工作。
标签: c++ class inheritance vector