2017-02-13 90 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

謝謝,夥計。它很好地工作。 –