這似乎是一個非常奇怪的情況。我只想繪制一個 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;
}
文本管理器標題:
#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
文本管理器 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 物件的副本。我嘗試了很多東西,比如回傳參考或常量參考等......我不明白。
我希望我的問題得到很好的展示。感謝您的幫助;-) 祝您有美好的一天!
uj5u.com熱心網友回復:
這個
TextManager textManager(); //My class that don't work...
是函式宣告,而不是物件的構造。應該:
TextManager textManager; //My class that don't work...
經過
sf::Text myText("Not drawn on the screen :-(",font);
您定義了一個myText與資料成員相同的區域變數。因此,myText回傳的getMyText不受影響。
編碼前閱讀檔案:
重要的是要注意 sf::Text 實體不會復制它使用的字體,它只保留對它的參考。因此,當 sf::Font 被 sf::Text 使用時,sf::Font 不能被破壞(即永遠不要撰寫使用本地 sf::Font 實體來創建文本的函式)。
取自SFML 參考。
class TextManager
{
public:
TextManager();
virtual ~TextManager();
sf::Text& getMyText(); // <- pass by reference
private:
sf::Font myFont;
sf::Text myText;
};
和
TextManager::TextManager()
{
myFont.loadFromFile("arial.ttf");
myText.setString("Not drawn on the screen :-(");
myText.setFont(myFont);
myText.setPosition(sf::Vector2f(164,0));
myText.setCharacterSize(25);
myText.setFillColor(sf::Color::Blue);
}
可能作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/345365.html
上一篇:C#如何在方法中參考物件
