首页 > 解决方案 > C++ 类成员是空指针

问题描述

我有一个类(呈现文本):

class TextRenderer {
public:
  TextRenderer();
  void RenderText(GLFWwindow *window, std::string text);
private:
  FT_Library ft;
  FT_Face face;
};

我在哪里初始化成员ftface在构造函数中

TextRenderer::TextRenderer() {
    FT_Library ft;
    FT_Face face;

    FT_Init_FreeType(&ft));
    FT_New_Face(ft, "Assets/monospace.ttf", 0, &face);
    FT_Load_Char(face, 3, FT_LOAD_RENDER);

}
void TextRenderer::RenderText(GLFWwindow *window, std::string text) {
  FT_GlyphSlot slot = face->glyph; //Shortcut
  ...
}

但是当我想这样使用它时:

  TextRenderer tr;
  while (cond) {
    tr.RenderText(consoleEngine.window, prefix + inp);
  }

我收到一条错误消息

Exception thrown: read access violation.
this->face was nullptr.

对于TextRenderer::RenterText函数的第一行。

我不明白这一点。变量 face 不是 TextRenderer 类的成员,因此应该可以访问它吗?

标签: c++class

解决方案


这些是构造函数中的函数局部变量。它们不同于类的成员变量。因此,在构造函数返回后,成员变量保持未初始化状态。

删除行:

FT_Library ft;
FT_Face face;

你的功能应该是:

TextRenderer::TextRenderer() {
    FT_Init_FreeType(&ft);
    FT_New_Face(ft, "Assets/monospace.ttf", 0, &face);
    FT_Load_Char(face, 3, FT_LOAD_RENDER);
}

我建议提高编译器的警告级别。编译器可能会警告您这些变量,即函数变量,会影响成员变量。


推荐阅读