如何在 function/method 中使用 sf::window
How can I use a sf::window in a function/method
我想制作一个 class,它接受一个 string
,并在 sfml
的一个盒子里给出 string
。为了使绘图更容易,我制作了一个函数,它接受一个 renderwindow
的指针并绘制带有文本的框(我还没有实现 Box )
但是当我 运行 它时,我得到一个错误,不允许读取这个
我已经尝试通过引用传递window,但是没有用,结果还是一样
//Textbox.h
class textbox
{
public:
sf::Text txtinbox;
void draw(sf::RenderWindow* on)
{
on->draw(this->txtinbox);
}//Error
textbox(std::string txinbox)
{
sf::Font font;
font.loadFromFile(fontfile);
sf::Text text(txinbox , font);
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color::White);
txtinbox = text;
}
~textbox()
{}
private:
};
您有未定义的行为。
继续site找到这句话:
It is important to note that the sf::Text instance doesn't copy the
font that it uses, it only keeps a reference to it.
还有这个
never write a function that uses a local sf::Font instance for
creating a text
现在看看你的构造函数:
{
sf::Font font; // LOCAL VARIABLE
font.loadFromFile(fontfile);
sf::Text text(txinbox , font); // GET REFERENCE TO LOCAL
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color::White);
txtinbox = text;
// LOCAL IS DELETED
// txtinbox HAS DANGLING REFERENCE
}
所以你必须延长 font
的生命周期,例如让它成为你 class 的数据成员。
class textbox
{
public:
sf::Text txtinbox;
sf::Font font;
textbox(std::string txinbox)
{
font.loadFromFile(fontfile);
我想制作一个 class,它接受一个 string
,并在 sfml
的一个盒子里给出 string
。为了使绘图更容易,我制作了一个函数,它接受一个 renderwindow
的指针并绘制带有文本的框(我还没有实现 Box )
但是当我 运行 它时,我得到一个错误,不允许读取这个
我已经尝试通过引用传递window,但是没有用,结果还是一样
//Textbox.h
class textbox
{
public:
sf::Text txtinbox;
void draw(sf::RenderWindow* on)
{
on->draw(this->txtinbox);
}//Error
textbox(std::string txinbox)
{
sf::Font font;
font.loadFromFile(fontfile);
sf::Text text(txinbox , font);
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color::White);
txtinbox = text;
}
~textbox()
{}
private:
};
您有未定义的行为。
继续site找到这句话:
It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it.
还有这个
never write a function that uses a local sf::Font instance for creating a text
现在看看你的构造函数:
{
sf::Font font; // LOCAL VARIABLE
font.loadFromFile(fontfile);
sf::Text text(txinbox , font); // GET REFERENCE TO LOCAL
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color::White);
txtinbox = text;
// LOCAL IS DELETED
// txtinbox HAS DANGLING REFERENCE
}
所以你必须延长 font
的生命周期,例如让它成为你 class 的数据成员。
class textbox
{
public:
sf::Text txtinbox;
sf::Font font;
textbox(std::string txinbox)
{
font.loadFromFile(fontfile);