c++ - C++ 类成员是空指针
问题描述
我有一个类(呈现文本):
class TextRenderer {
public:
TextRenderer();
void RenderText(GLFWwindow *window, std::string text);
private:
FT_Library ft;
FT_Face face;
};
我在哪里初始化成员ft
和face
在构造函数中
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 类的成员,因此应该可以访问它吗?
解决方案
这些是构造函数中的函数局部变量。它们不同于类的成员变量。因此,在构造函数返回后,成员变量保持未初始化状态。
删除行:
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);
}
我建议提高编译器的警告级别。编译器可能会警告您这些变量,即函数变量,会影响成员变量。
推荐阅读
- r - R test if value is lowest from group, add 'yes'/'no' in new column if value is lowest from group
- python - 使用 Plotly 和 Numpy 从坐标绘制一个框
- php - MySQL 数据库未在 PHP 中接收任何数据
- dynamic - 具有动态命名范围的 EXCEL INDIRECT 函数
- python - 使用键侦听器 (pynput) 遍历列表,而无需手动复制单词
- python - 无法将日期时间值转换为必要的格式
- transactions - etherscan如何获得区块链编译代码?
- qt - 使用网络服务异步填充 qabstractitemmodel
- web-scraping - 如何在 scrapy.selector.unified.SelectorList 上迭代地使用 xpath?
- python - KMeans clustering from all possible combinations of 2 columns not producing correct output