2017-02-13 38 views
1

我构建了一个应用程序两次:一次在Visual Studio中,另一次在XCode中。我使用的一个库,GLFW,允许您使用glfwSetWindowSizeCallback函数来检测窗口的大小调整。如何在OSX上声明静态C++函数作为朋友

我的窗口类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); 
} 

没有朋友的关键字,window_size_callback无法访问这些成员。

为什么VS和这很好,而XCode不是?

而且,如何避免使用setter?

+0

静态朋友有什么意义?无论如何,朋友函数并不是类的一部分......代码段也是千言万语。 – DeiDei

+0

当窗口调整大小时,它需要成为朋友才能修改我的班级的私人成员@DeiDei –

+0

然后让它成为朋友,但为什么它需要是静态的? – DeiDei

回答

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允许语法作为扩展。不要指望它。

+0

谢谢,伙计。它很好地工作。 –