【发布时间】: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