[英]Accessing an object from a vector of object pointers
This is a bit code i'm having trouble with: 这是我遇到麻烦的一点代码:
int pressedKey = event.getNativeKeyCode();
for (int i=0; i <= AllTriggerPads.size() ;i++) {
if (AllTriggerPads[i]->get_key() == pressedKey){
AllTriggerPads[i]->mBufferPlayerNode->start();
}
}
the get_key()
is getting a EXC_BAD_ACCESS (Code=1, ...)
Error. get_key()
收到EXC_BAD_ACCESS (Code=1, ...)
错误。
I seem to have a referencing problem. 我似乎有一个参考问题。 I am using almost the same code in the mouseDown and the fileDrop function:
我在mouseDown和fileDrop函数中使用几乎相同的代码:
for (int i=0; i < AllTriggerPads.size() ; i++) {
if (AllTriggerPads[i]->mRect.contains(event.getPos())) {
AllTriggerPads[i]->mBufferPlayerNode->start();
}
}
This works fine! 这样很好!
Sooooo, i guess i am using the AllTriggerPads vector (of obj pointers) not correctly. 太好了,我想我没有正确使用(obj指针的)AllTriggerPads向量。 So I CAN use
AllTriggerPads[i]->mRect.contains(event.getPos())
but I CANT use AllTriggerPads[i]->get_key()
. 所以我可以使用
AllTriggerPads[i]->mRect.contains(event.getPos())
但我不能使用AllTriggerPads[i]->get_key()
。 And I CANT access the value itself by AllTriggerPads[i]->key
I have tried it with AllTriggerPads.at(i)
but then i get an out of range error which makes me wonder even more. 我无法通过
AllTriggerPads[i]->key
访问值本身,而我已经使用AllTriggerPads.at(i)
尝试过它,但是随后出现了超出范围的错误,这使我感到更加疑惑。
The AlltriggerPads was initialized with vector<TriggerPad*> AllTriggerPads;
AlltriggerPads用
vector<TriggerPad*> AllTriggerPads;
初始化vector<TriggerPad*> AllTriggerPads;
So how can I access the key member? 那么我该如何访问关键成员?
You are having an off-by-one error. 您遇到一个错误的错误。
for (int i=0; i <= AllTriggerPads.size() ;i++)
replace with 用。。。来代替
for (int i=0; i < AllTriggerPads.size(); ++i)
(The ++ thing is irrelevant, it's just better practice to always use pre-increment) (++无关紧要,始终使用预增量只是更好的做法)
You are trying to access an array element which doesn't exist. 您正在尝试访问不存在的数组元素。 That's why it throws
EXC_BAD_ACCESS
. 这就是为什么它抛出
EXC_BAD_ACCESS
的原因。 Change the for loop conditional to 将for循环条件更改为
for (int i = 0; i < AllTriggerPads.size(); ++i) {
if (AllTriggerPads[i]->get_key() == pressedKey) {
AllTriggerPads[i]->mBufferPlayerNode->start();
}
}
or if C++11
support is enabled, simplify it to 或者如果启用了
C++11
支持,则将其简化为
for (auto i : AllTriggerPads) {
if (i->get_key() == pressedKey) {
i->mBufferPlayerNode->start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.