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

时间:2017-02-13 04:36:26

标签: c++ xcode macos visual-c++ glfw

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

我的窗口类Window有两个私有成员,宽度和高度。在调用我的回调函数window_size_callback时,我希望更新宽度和高度的值。但是,我想在不使用setter的情况下这样做。

所以,我让window_size_callback成了一个静态的朋友。这个解决方案在Visual Studio编译器中运行得很好;但是,XCode返回了一个错误:'static'在好友声明中无效。

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没关系?

而且,如何在不使用setter的情况下解决这个问题?

1 个答案:

答案 0 :(得分:1)

只需删除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允许语法作为扩展。别指望它。

相关问题