我正在创建一个对象并将其添加到 a 中std::vector
,然后访问std::vector
以使用我放置在其中的对象中的成员变量。
.h 包含std::vector
std::vector<Field *> vFields;
inline std::vector<Field *> getFields() { return vFields; };
在 .cpp 我这样做:
Field* f1 = Field::createWithLocation(ccp( p.x, p.y));
addChild(f1->getFieldSprite(), 2);
getFields().push_back(f1); // add the new field to a container
//vFields.push_back(f1); // add the new field to a container
std::cout << "add - # of Fields: " << getFields().size() << std::endl;
实例化Field* f1
上述情况时,会发生这种情况:
Field* Field::createWithLocation(cocos2d::CCPoint p)
{
Field* f = new Field();
//f->autorelease();
f->initWithLocation(p);
return f;
}
void Field::initWithLocation(cocos2d::CCPoint p)
{
setFieldCenterPoint(p);
setFieldGraphicName(FIELD::fieldIconFileName);
setFieldSprite(cocos2d::CCSprite::create(getFieldGraphicName().c_str()));
getFieldSprite()->setPosition(ccp(getFieldCenterPoint().x, getFieldCenterPoint().y));
setFieldSize(getFieldSprite()->getContentSize());
setFieldNumber(7159);
setFieldTag(7159);
std::cout << "When Field Created #: " << getFieldTag() << std::endl;
}
这很好用,当Field
创建对象时,std::vector 会说1
insize()
并且 getFieldTag()7159
会像设置一样返回。
问题是当我Field
从向量访问时发生了一些事情并且我崩溃了。我发现,如果我输出 getTagNumber() ,那就大不相同了。
访问向量的示例:
else if (getFieldLayerState() == kActive)
{
// so did they click on a field?
std::cout << "Field Layer Status Is Active" << std::endl;
std::cout << "touch - # of Fields: " << vFields.size() << std::endl;
// Loop through the field vector and get the size of each field and see if it was tapped
for (int f=0; f<vFields.size(); f++)
{
//field = (Field*) getFields().at(f);
Field* field = (Field*) vFields.at(f);
std::cout << "field #: "<< field->getFieldNumber() << std::endl;
std::cout << "field tag: "<< field->getFieldTag() << std::endl;
if (field->getFieldSprite()->boundingBox().containsPoint(location))
{
std::cout << "touched field #: "<< field->getFieldNumber() << std::endl;
std::cout << "touched field tag: "<< field->getFieldTag() << std::endl;
_dir->Instance()->getAudioEngine()->playBackgroundMusic("tap.mp3", false);
}
}
}
cout 语句的示例输出:
When Field Created #: 7159
add - # of Fields: 1
Field Layer Status Is Active
touch - # of Fields: 1
field #: 1769234804
field tag: 353394533`
if (field->getFieldSprite()->boundingBox().containsPoint(location))
我在上面的行中崩溃了EXEC_BAD_ACCESS
,很明显,向量中的内容与我放入的内容有所不同,或者看起来是这样。
谁能帮我理解我做错了什么?