这是一个最小的可重现示例:
#include <memory>
#include <SFML/Graphics.hpp>
class Label
{
public:
Label(sf::String msg, float y)
{
if (!font.loadFromFile("arial.ttf"))
{
printf("Error loading font!\n");
}
text.setString(msg);
text.setPosition(0, y);
}
sf::Font font;
sf::Text text = sf::Text("Label", font, 40);
};
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
// label is a local variable
Label label1 = Label("Label1", 0);
// label is inside a pointer
std::unique_ptr<Label> label2 = std::make_unique<Label>("Label2", 50);
struct Labelstruct
{
Label label;
};
// label is inside a struct
struct Labelstruct label3 = { Label("Label3", 100) };
// label is inside a struct inside a pointer:
std::unique_ptr<Labelstruct> label4 = std::make_unique<Labelstruct>(Label("Label4", 150));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(label1.text);
window.draw(label2->text);
window.draw(label3.label.text);
window.draw(label4->label.text);
window.display();
}
return EXIT_SUCCESS;
}
解释:类
Label
封装了 sf::Text
。然后我使用四种不同的方式来初始化和绘制它:
“Label4”未绘制。我可以看到标签应该出现的点:
为什么指向结构体的指针会导致这个问题?
为了您的方便,这是我用来编译该东西的命令:
g++ test.cc -std=c++20 -lsfml-window -lsfml-system -lsfml-graphics