c++ - 如何将成员指针初始化为自由函数?
问题描述
我正在尝试创建一个带有指针的类,可以在类之外进行更改。无论我做什么,我要么得到语法错误,要么指针根本没有初始化我有以下代码:
窗口.h
#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
class window
{
public:
GLFWwindow* wnd;
window(int width, int height, const char* title);
void close();
void (*update)(window*);
void (*draw)(window*);
void run();
void setDrawFunction(void (*fnptr)(window*));
void setUpdateFunction(void (*fnptr)(window*));
};
窗口.cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "window.h"
void default_draw(window* wnd) {
glClear(GL_COLOR_BUFFER_BIT);
}
void default_update(window* wnd) {
}
window::window(int width, int height, const char* title)
{
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_COMPAT_PROFILE, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
wnd = glfwCreateWindow(width, height, title, NULL, NULL);
if (wnd == NULL) { glfwTerminate(); return; }
glfwMakeContextCurrent(wnd);
if (glewInit() != GLEW_OK) {
glfwTerminate();
return;
}
//This does not work
draw = default_draw;
update = default_update;
}
void window::close() {
glfwDestroyWindow(wnd);
}
void window::setDrawFunction(void(*fnptr)(window*)) {
// And so does this
draw = fnptr;
}
void window::setUpdateFunction(void(*fnptr)(window*)) {
update = fnptr;
}
void window::run() {
while (glfwWindowShouldClose(wnd) == 0)
{
glClear(GL_COLOR_BUFFER_BIT);
//update(this);
draw(this); // This will cause attempt to access 0x0000000000000
glfwSwapBuffers(wnd);
glfwPollEvents();
}
close();
}
我已经尝试了很多东西,但它们没有用。难道我做错了什么?我需要使用指针,因为上面的这个东西是稍后使用 ctypes 包装到 python 中的简单引擎的一部分。
编辑:以前的版本可能有点不清楚。我遇到问题的部分是绘图功能。我试图声明一个指向自由函数的指针,然后在构造函数和函数中设置它。问题是,该变量显然没有正确设置。
解决方案
不要使用原始函数指针,而是使用 std::function:
窗口.h:
#include <functional>
// [...]
class window {
// [...]
public:
std::function<void(window *)> update;
std::function<void(window *)> draw;
// [...]
}
窗口.cpp:
void window::setDrawFunction(std::function<void(window *)> fnptr) {
draw = fnptr;
}
void window::setUpdateFunction(std::function<void(window *)> fnptr) {
update = fnptr;
}
通过查看https://en.cppreference.com/w/cpp/utility/functional/function了解更多信息。
您可以使用如下初始化列表在类构造函数中初始化此函数:
window::window(int width, int height, const char* title)
: update(default_update), draw(default_draw)
{
// [...]
}
推荐阅读
- go - 将 cloudevents 格式的数据发送到 Kafka 主题
- postgresql - 移动 docker-compose.yml 创建一个新的 postgres 数据库
- matomo - 错误:在模块“API”中找不到操作“Iframe”
- azure - 与 Azure DevOps Server 2020 共享 Azure DevOps 门户
- css - 消除图像和行边界之间的间隙
- database - Oracle 中的批量选择和插入
- python - Python,Pandas 数据透视表:如何获得 SubCount 的总和?
- sql - 显示列中重复项的单个结果并包括剩余的表结果
- javascript - 如何以角度在 I-Frame 和父窗口之间进行通信
- three.js - 如何添加一个对象取决于三个js中的线(墙)?