如何在 OSX 上将静态C++函数声明为好友

How to declare static C++ function as friend on OSX

本文关键字:函数 C++ 声明 好友 静态 OSX      更新时间:2023-10-16

我已经构建了两次应用程序:一次在Visual Studio中,另一次在XCode中。我使用的一个库 GLFW 允许您使用 glfwSetWindowSizeCallback 函数来检测窗口的大小调整。

我的窗口类 Window 有两个私有成员,宽度和高度。在调用我的回调时,window_size_callback,我希望更新宽度和高度的值。但是,我想在不使用二传手的情况下做到这一点。

所以,我把window_size_callback交成了一个静态的朋友。这个解决方案在Visual Studio编译器中工作得很好;但是,XCode 返回了一个错误:"静态"在友元声明中无效。

window_size_callback

void window_size_callback(GLFWwindow* window, int width, int height) {
    Window* win = (Window*)glfwGetWindowUserPointer(window);
    win->width = width;
    win->height = height;
}

glfwGetWindowUserPointer用于从类外部获取当前窗口实例。

头文件:

#include <GLFW/glfw3.h>
class Window {
private:
    int m_width;
    int m_height;
private:
    friend static void window_size_callback(GLFWwindow* window, int width, int height);
}

如果没有 friend 关键字,window_size_callback 无法访问这些成员。

为什么 VS 对此很好,而 XCode 则不行?

而且,如何在不使用二传手的情况下解决此问题?

只需删除static即可。正如我在评论中解释的那样,这毫无意义。这是一个应该清除事情的片段:

class Window {
private:
    int m_width;
    int m_height;
private:
    friend void window_size_callback(GLFWwindow*, int, int);
};
// as you can see 'window_size_callback' is implemented as a free function
// not as a member function which is what 'static' implies
void window_size_callback(GLFWwindow* window, int width, int height) {
    Window* win = (Window*)glfwGetWindowUserPointer(window);
    win->width = width;
    win->height = height;
}

friend函数不能是类的static成员。我猜 VS 允许语法作为扩展。不要指望它。