嵌套构造函数 C++

Nested Constructors C++

我正在使用 SFML 并且 class 如下所示:

#include <SFML\Graphics.hpp>

class Overlay
{
public:
    Overlay(int width, int height);
    Overlay(const sf::Texture*);
    Overlay(const sf::Sprite*);

    ~Overlay();

private:
    sf::Texture _texture;
    sf::Image _img;
};

现在 Overlay(const sf::Sprite*) 的以下构造函数正在运行:

Overlay::Overlay(const sf::Sprite* spr) {    
    int width = spr->getTexture()->getSize().x;
    int height = spr->getTexture()->getSize().y;
    _texture.create(width, height);
    _img.create(width, height, sf::Color::Transparent);
}

但是,以下嵌套构造函数不是:

Overlay::Overlay(int width, int height)
{
    _texture.create(width, height);
    _img.create(width, height, sf::Color::Transparent);
}

Overlay::Overlay(const sf::Texture* tex) {
    sf::Vector2u textureSize = tex->getSize();
    Overlay(textureSize.x, textureSize.y);
}

Overlay::Overlay(const sf::Sprite* spr) {
    Overlay(spr->getTexture());
}

在我看来,如果执行以下操作,这两个片段应该做同样的事情:

sf::Sprite image;
Overlay mOverlay(&image);

虽然它们都编译得很好,但是当调用第二个代码片段(嵌套构造函数)时,_img 的大小最终为 0,其 m_pixels 数组为空。

委派构造函数。

听起来您正在寻找 Delegating Constructor

要使用委托构造函数,它应该出现在另一个构造函数的 成员初始值设定项列表 中,而不是构造函数的 主体 .

在您的第二个代码段中,您正在构造一个临时 Overlay 对象堆栈。构造函数returns时,临时被销毁,没有作用

尝试像这样定义构造函数:

Overlay::Overlay(const sf::Sprite& spr)
    : Overlay(spr.getTexture())
{
}

一次小型代码审查。

注意到我是如何使用 const sf::Sprite& 而不是 const sf::Sprite* 的吗?因为没有处理 sprnullptr 的情况,所以通过引用传递它以确保它引用一个对象是有意义的。这也解决了关于调用构造函数后谁拥有纹理的任何问题。

执行此操作时,还应考虑使用 explicit keyword 声明构造函数,如下所示:

class Overlay
{
public:
    explicit Overlay(const sf::Texture&);
    explicit Overlay(const sf::Sprite&);
};

这可以防止 TextureSprite 在传递它们时意外地变成 Overlay