我正在尝试将对象保存为2D向量。矢量需要在运行时调整大小。因此,我使用了其他许多问题中提到的调整大小功能。
她是我的问题的分解代码示例。因此,代码可能没有意义,但是我遇到了相同的错误。
Animation.h
class myPoint{
public:
int x, y;
myPoint(){}
myPoint(int x, int y) : x(x), y(y) {}
};
class AnimationFrame {
private:
std::vector<std::vector<myPoint>> sprites; //the important part
public:
void addSpritePoint(myPoint gridPos, myPoint tilePos);
...
};
class Animation {
private:
std::vector<AnimationFrame*> animationFrames;
public:
...
};
Animation.cpp
Animation::Animation() {}
int Animation::addAnimationFrame() {
AnimationFrame *newAnimationFrame = new AnimationFrame();
this->animationFrames.emplace_back(newAnimationFrame);
}
//AnimationFrame class
AnimationFrame::AnimationFrame(){
int w = 3; //just for the test
int h = 3;
this->sprites.resize(w, std::vector<myPoint>(h, myPoint(0,0)));
}
void AnimationFrame::addSpritePoint(myPoint gridPos, myPoint tilePos) {
this->sprites[gridPos.x][gridPos.y] = tilePos;
//printf(""); //breakpoint here
}
main.cpp
int main() {
Animation *a = new Animation();
a->addAnimationFrame();
a->getAnimationFrame(0).addSpritePoint(myPoint(0,0), myPoint(1,1));
a->getAnimationFrame(0).addSpritePoint(myPoint(0,1), myPoint(2,2));
a->getAnimationFrame(0).addSpritePoint(myPoint(0,2), myPoint(3,3));
}
我希望我的AnimationFrame类中的Sprite 2D矢量可以保存这些值。当第一个断点出现在Point(1,1)时位于sprites(0,0)中,但是当我现在跳至下一个断点时,sprites(0,0)中的值再次变为(0,0)。因此,它将重置该值。而且我不知道为什么。
答案 0 :(得分:0)
问题来自Animation::getAnimationFrame()
返回其内部数据的副本的事实:
AnimationFrame Animation::getAnimationFrame(int frame) const;
因此,它修改了一个临时对象,并且在对完整表达式求值后无效:
a->getAnimationFrame(0).addSpritePoint(myPoint(0,0), myPoint(1,1));
解决方法很简单:按引用返回:
const AnimationFrame& Animation::getAnimationFrame(int frame) const
{
return *animationFrames[frame];
}
AnimationFrame& Animation::getAnimationFrame(int frame)
{
return *animationFrames[frame];
}
(是的,您需要一个const和一个非const版本)