【问题标题】:Loading a Font in a class in SFML在 SFML 的类中加载字体
【发布时间】:2020-06-01 19:40:44
【问题描述】:

我在将字体加载为自定义类的静态成员时遇到问题。

我已尝试按照 SFML 教程进行操作,但我显然遗漏了一些步骤!

代码如下:

#include <string>
#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <random>
#include <chrono>
#include <math.h>

using namespace std;
using namespace sf;

class base
{
    int number;
    double radius;
    double last_update_time;
    public:
        static const string FontFile = "SugarpunchDEMO.otf";
        static bool Init(const string& FontFile)
        {
            return font.loadFromFile(FontFile);
        }
        CircleShape shape;
        Text text;
        static Font font;
        void update_number(double time, double &last_update_time, int &number);
        void update_radius(int number, double &radius);
        base(int ini_number, double pos_x, double pos_y, double time);
        void update(double time);
};

构造函数是:

base::base(int ini_number, double pos_x, double pos_y, double time){
    number = ini_number;
    update_radius(number, radius);
    shape.setRadius(radius);
    shape.setFillColor(Color::Red);
    shape.setPosition(pos_x - radius, pos_y - radius);
    text.setFont(font);
    char name[32];
    sprintf(name,"%d",number);
    text.setString(name);
    text.setCharacterSize(200); 
    text.setFillColor(sf::Color::Blue);
    text.setPosition(pos_x,pos_y);
    last_update_time = time;
}

目标是只加载一次字体并将其应用于类的每个成员。

我得到的错误是:

In file included from base.cpp:9:0:
base.hpp:19:29: error: in-class initialization of static data member ‘const string base::FontFile’ of non-literal type
         static const string FontFile = "SugarpunchDEMO.otf";
                             ^~~~~~~~
base.hpp:19:40: error: call to non-constexpr function ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
         static const string FontFile = "SugarpunchDEMO.otf";
                                        ^~~~~~~~~~~~~~~~~~~~

【问题讨论】:

    标签: c++ class sfml static-members


    【解决方案1】:

    您的错误消息指出,此问题与 SFML 无关:

    非文字类型的静态数据成员const string base::FontFile的类内初始化

    或者换句话说:这种初始化类成员的方式只允许用于数值和指向(字符串)文字的指针。您正在尝试初始化所述类的 std::string 对象。

    作为一种解决方案,将const char* 用于FontFile 或将初始化移动到您的实现文件中作为const std::string FontFile = "SugarpunchDEMO.otf";

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 2016-03-29
      • 2020-11-05
      • 1970-01-01
      • 2014-08-13
      • 2014-02-25
      • 1970-01-01
      • 2018-08-26
      相关资源
      最近更新 更多