SFML C++ - 制作基本 Window 的代码在分开时不起作用

SFML C++ - Code to Make Basic Window Won't Work When Divided

我正在测试 SFML 和结构,所以我决定用 C++ 编写这一小段代码,但失败了:

/tmp/ccudZjgy.o: In function `fontconfig()':
main.cpp:(.text+0x96): undefined reference to `Text::font'
/tmp/ccudZjgy.o: In function `textconfig()':
main.cpp:(.text+0x146): undefined reference to `Text::font'
main.cpp:(.text+0x1fa): undefined reference to `Text::text'
/tmp/ccudZjgy.o: In function `window()':
main.cpp:(.text+0x3d8): undefined reference to `Text::text'
collect2: error: ld returned 1 exit status

这是我的代码:

#include <SFML/Graphics.hpp>

struct Text{
     static sf::Font font;
     static sf::Text text;  
};
void fontconfig()
{
     sf::Font font;
     font.loadFromFile("flower.ttf");
     Text Text1;
     Text1.font = font;
}

void textconfig()
{
     Text Text1;
     sf::Text text;
     text.setFont(Text1.font);
     text.setCharacterSize(100);
     text.setColor(sf::Color::Red);
     text.setString("Ugh...");
     text.setStyle(sf::Text::Bold);

     Text1.text = text;
}

 void window()
 {
        Text Text1;
        sf::RenderWindow window(sf::VideoMode(300, 150), "Hello");
        while (window.isOpen())
        {
              sf::Event event;
              while (window.pollEvent(event))
              {
                     if (event.type == sf::Event::Closed)
                     window.close();
              } 

              window.clear(sf::Color::White);
              window.draw(Text1.text);
              window.display();

              } 


}
int main()
{
 fontconfig();
 textconfig();
 window();
 return 0;
}

函数中的变量是局部变量。由于命名空间的工作方式,首先引用与全局变量同名的局部变量,如果需要,可以在前面加上双冒号来引用全局变量:

Foo // refers to the default, local scope

::Foo // refers to the global scope

换句话说,您实际上从未接触过全局变量。

相反,当您离开函数作用域时,您修改的局部变量将被丢弃。

相反,如果您希望使用子例程、增变器样式,您应该将外部资源 类 作为参数引用传递给函数,如下所示:

void textconfig(sf::Text& text); // pass by reference for a subroutine-focused, mutator style