[英]C++ Am I adding and accessing my Vector correctly?
我正在創建一個對象並將其添加到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的size()
表示為1
,而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
並使用了EXEC_BAD_ACCESS
,很明顯,向量中的內容與我放入的內容有所不同,或者如此似乎。
誰能幫助我了解我做錯了什么?
您的getFields
函數返回向量的副本 。 因此,對返回向量的任何更改都只會在副本中發生,而不會在原始副本中發生。
您想返回參考 。
std::vector<Field*>& getFields() { return vFields; }
// ^
// Note the ampersand
您可能還希望添加該const
重載:
const std::vector<Field*>& getFields() const { return vFields; }
// ^ ^
// Note the two `const` modifiers, the last one is important
然后,如果您修改了向量,例如通過添加向量,編譯器將選擇第一個非常量重載。 而且,如果您不修改向量,例如,僅在向量上調用size
時,編譯器將選擇第二個const重載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.