我正在创建一个对象并将其添加到 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()
和 getFieldTag() 中显示 1
返回 7159
就像设置的一样。
问题是当我从 vector 访问Field
时,会发生一些事情并且我崩溃了。我发现如果我输出 getTagNumber() ,情况会有所不同。
访问 vector 的示例:
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
,很明显 vector 中的内容与我放入其中的内容发生了变化,或者看起来是这样。
谁能帮助我理解我做错了什么?
最佳答案
您的 getFields
函数返回 vector 的拷贝。因此,对返回 vector 的任何更改只会发生在拷贝中,而不是原始 vector 中。
您想要返回一个引用。
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
然后如果你修改 vector ,例如通过添加它,编译器将选择第一个非常量重载。如果你不修改 vector ,例如当您仅在 vector 上调用 size
时,编译器将选择第二个 const 重载。
关于C++ 我是否正确添加和访问我的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17383944/