【问题标题】:Nested Constructors C++ [duplicate]嵌套构造函数 C++ [重复]
【发布时间】:2023-04-03 23:48:01
【问题描述】:

我正在使用 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;
};

现在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());
}

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

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

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

【问题讨论】:

  • 不确定“嵌套构造函数”是什么意思。您是否期望这些构造函数主体调用同一对象上的其他构造函数?这不是它的工作原理。您不能像函数一样“调用”构造函数。你所做的只是创造一些临时的。在您的 C++ 书籍中查找“委托构造函数”。
  • @LightnessRacesinOrbit 好吧,那是……尴尬……
  • 好吧,它发生了:)

标签: c++ constructor nested sfml


【解决方案1】:

委托构造函数。

听起来您正在寻找Delegating Constructor。

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

在您的第二个 sn-p 中,您正在构建一个临时的 Overlay 对象堆栈。当构造函数返回时,临时对象被销毁,没有任何作用。

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

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

一个小的代码审查。

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

当你这样做时,你还应该考虑使用explicit keyword 声明构造函数,如下所示:

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

这可以防止Textures 和Sprites 在传递它们时意外变成Overlays。

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多