嵌套构造函数C ++

Pro*_*000 2 c++ constructor nested sfml

我正在使用SFML,并且具有类似以下的类:

#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;
};
Run Code Online (Sandbox Code Playgroud)

现在,以下构造函数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);
}
Run Code Online (Sandbox Code Playgroud)

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

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());
}
Run Code Online (Sandbox Code Playgroud)

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

sf::Sprite image;
Overlay mOverlay(&image);
Run Code Online (Sandbox Code Playgroud)

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

Sea*_*ine 5

委托构造函数。

听起来您正在寻找委派构造函数

要使用委托的构造函数,它应该出现在另一个构造函数的成员初始化器列表中,而不是出现在构造函数的body中

在第二个代码段中,您将Overlay在堆栈中构造一个临时对象。当构造函数返回时,该临时对象将被销毁,并且无效。

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

Overlay::Overlay(const sf::Sprite& spr)
    : Overlay(spr.getTexture())
{
}
Run Code Online (Sandbox Code Playgroud)

小代码审查。

注意我是如何使用a const sf::Sprite&而不是a的const sf::Sprite*?因为不是处理spra 的情况nullptr,所以有必要通过引用传递它以确保它引用了一个对象。这也清除了有关构造函数被调用后谁拥有纹理的任何问题。

在执行此操作时,还应考虑使用如下explicit关键字声明构造函数:

class Overlay
{
public:
    explicit Overlay(const sf::Texture&);
    explicit Overlay(const sf::Sprite&);
};
Run Code Online (Sandbox Code Playgroud)

这样可以防止Textures和Sprites Overlay在传递时意外地变成s。