[英]How to initialize member pointer to free function?
我正在尝试创建一个带有指针的 class,它可以在 class 之外更改。 无论我做什么,我要么得到语法错误,要么指针根本没有初始化我有以下代码:
window.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*));
};
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 中。
编辑:以前的版本可能有点不清楚。 我遇到问题的部分是绘制 function。 我试图声明一个指向空闲 function 的指针,然后在构造函数和 function 中设置它。 问题是,该变量显然没有正确设置。
不要使用原始 function 指针,而是使用 std::function:
window.h:
#include <functional>
// [...]
class window {
// [...]
public:
std::function<void(window *)> update;
std::function<void(window *)> draw;
// [...]
}
window.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了解更多信息。
您可以使用如下初始化列表在 class 构造函数中初始化此函数:
window::window(int width, int height, const char* title)
: update(default_update), draw(default_draw)
{
// [...]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.