【发布时间】:2021-12-15 19:03:34
【问题描述】:
这似乎是一个非常奇怪的情况。我只想绘制一个 sf::Text 对象,它在主循环之外(在另一个类中)处理。
我只给你看基本的。这段代码有效(它绘制了其他直接在 main 中处理的东西),因此它可以编译。
主要:
int main()
{
//we handle the creation of the window //
//...
//Example where the sf::Text is handle in the main (it works)
sf::Font font;
font.loadFromFile("arial.ttf");
sf::Text mainTxt("It works !!",font);
mainTxt.setPosition(sf::Vector2f(64,"It works !!"));
mainTxt.setCharacterSize(25);
mainTxt.setFillColor(sf::Color::Blue);
TextManager textManager(); //My class that don't work...
sf::Event event;
while (window.isOpen())
{
// We handle event (we don't care here)
// ...
window.draw(mainTxt); // it works
window.draw(textManager.getMyText()); // do nothing
window.display();
window.clear();
}
return 0;
}
TextManager 标题:
#ifndef TEXTMANAGER_H
#define TEXTMANAGER_H
#include <SFML/Graphics.hpp>
class TextManager
{
public:
TextManager();
virtual ~TextManager();
sf::Text getMyText();
private:
sf::Text myText;
};
#endif // TEXTMANAGER_H
TextManager cpp
#include "TextManager.h"
TextManager::TextManager()
{
sf::Font font;
font.loadFromFile("arial.ttf");
sf::Text myText("Not drawn on the screen :-(",font);
myText.setPosition(sf::Vector2f(164,0));
myText.setCharacterSize(25);
myText.setFillColor(sf::Color::Blue);
}
// in this example (that do not work) I do not change fspText. But, I want to update it at each call of the get function. So, it is not a constant class member.
sf::Text TextManager::getMyText() {
return myText;
}
TextManager::~TextManager()
{
//dtor
}
我真正不明白的是,使用我的自定义类,我可以使用这种类型的 getter 访问类成员对象。我也做了一些研究,我认为它应该返回 sf::Text 对象的副本。 我尝试了很多东西,比如返回引用或常量引用等......我不明白。
我希望我的问题得到很好的展示。 谢谢您的帮助 ;-) 祝你有美好的一天!
【问题讨论】:
-
可以引用窗口并在类函数中使用绘图函数。但是我不想用之前的方法来理解我做错了什么。
标签: c++ class object sfml getter