c ++如何将范围保持在范围内?

时间:2016-10-26 04:02:31

标签: c++ sfml

更具体地说,我有一个看起来像这样的课程:

class Ball {
    public:
        unsigned collider_size;
        scionofbytes::MovementComponent movement;
        scionofbytes::GraphicComponent graphic;

        Ball(u_int init_collider_size, std::string texture_path) {
            collider_size = init_collider_size;
            movement = scionofbytes::MovementComponent();
            graphic = scionofbytes::GraphicComponent(
                    (u_int) collider_size/2,
                    (u_int) collider_size/2,
                    texture_path
            );
        }
};

我正在接受texture_path并将其传递给图形组件,如下所示:

class GraphicComponent {
    unsigned height;
    unsigned width;

    public:
        sf::Texture texture;
        sf::Sprite sprite;

        GraphicComponent() {}

        GraphicComponent(unsigned init_height, unsigned init_width, std::string texture_path) {
            width = init_width;
            height = init_height;

            texture.loadFromFile(texture_path);
            sprite.setTexture(texture);
        }
};

当我通过传入texture_path实例化一个球对象时,我正在创建一个纹理作为图形组件的一个成员,然后将该纹理分配给图形组件的精灵成员。

当使用此精灵成员绘制到屏幕时,我面临着SFML已知的white box problem

根据我的理解,球对象保持活着状态,图形组件成员也像图形组件的纹理成员一样保持活着。

所以我的问题是,为什么这不起作用?当使用精灵在屏幕上绘图时,我仍然得到一个白色的盒子。为什么纹理会被破坏?

1 个答案:

答案 0 :(得分:2)

((Z - 'A') * 26 + (X - 'A')) * 10000 + YYYY 类构造函数中,您正在对Ball进行复制。 IIRC GraphicComponent仅保留对sf::Sprite的引用,因此您的副本可能会以sf::Texture从其复制的对象中指向已删除的sf::Sptite结束。

尝试构建sf::Texture 而不制作Ball的副本:

GraphicComponent

此外你可能还想为你的class Ball { public: unsigned collider_size; scionofbytes::MovementComponent movement; scionofbytes::GraphicComponent graphic; // Use initializer-list Ball(u_int init_collider_size, std::string texture_path) : collider_size(init_collider_size) , movement() , graphic((u_int) collider_size/2, (u_int) collider_size/2, texture_path) { // don't assign stuff here if you can avoid it } }; 类创建一个复制构造函数,以防止其他地方出现腐败:

GraphicComponent
相关问题