簡體   English   中英

如何初始化成員指針以釋放 function?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM