gpt4 book ai didi

c++ - 未初始化的引用成员

转载 作者:IT老高 更新时间:2023-10-28 21:37:31 25 4
gpt4 key购买 nike

基本上我想做的是将 Sprite 的事件动画的引用存储为 Actor 类中的私有(private)成员。我想使用引用,因此我不必多次实际创建动画,但我一直收到错误。

Actor 类声明:

class Actor
{
public:
Actor();
~Actor();
void setActiveAnimation(Animation anim);
void draw(sf::RenderWindow& win);

private:
sf::Sprite sprite;
MaJR::Animation& activeAnimation;
};

Actor 类实现:

Actor::Actor()
{
// constructor
}

Actor::~Actor()
{
// destructor
}

void Actor::setActiveAnimation(Animation anim)
{
activeAnimation = anim;
activeAnimation.gotoStart();
}

void Actor::draw(sf::RenderWindow& win)
{
sprite.setTexture(activeAnimation.getActiveFrame());
win.draw(sprite);
activeAnimation.nextFrame();
}

构建输出:

/home/mike/MaJR Game Engine/src/Actor.cpp||In constructor 'MaJR::Actor::Actor()':|
/home/mike/MaJR Game Engine/src/Actor.cpp|8|error: uninitialized reference member 'MaJR::Actor::activeAnimation' [-fpermissive]|
||=== Build finished: 1 errors, 0 warnings ===|

最佳答案

一个引用不能重新分配,所以它必须在member-initialization-list中初始化。但是,您打算重新分配它,因此您想要的不是引用。更重要的是,在您的 setActiveAnimation 函数中,您将此类引用设置为作为参数传递的值的拷贝,这会在代码退出函数时给您留下无效的引用。也许指针会适合你?

在类体内:

MaJR::Animation* activeAnimation;

以及setActiveAnimation函数:

void Actor::setActiveAnimation(Animation* anim)
{
activeAnimation = anim;
activeAnimation->gotoStart();
}

关于c++ - 未初始化的引用成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com