2012-11-01 45 views
0

我對類感到困惑,希望有人能夠解釋。與類中的變量混淆

我有一堂課正在爲遊戲菜單創建按鈕。有四個變量:

int m_x int m_y int m_width int m_height

我則想用渲染功能的類,但林不理解我如何使用4個INT變量在類並把它傳遞給在課堂上的功能?

我的班級是這樣的:

class Button 
{ 
private: 
    int m_x, m_y;   // coordinates of upper left corner of control 
    int m_width, m_height; // size of control 

public: 
Button(int x, int y, int width, int height) 
{ 
    m_x = x; 
    m_y = y; 
    m_width = width; 
    m_height = height; 
} 

void Render(SDL_Surface *source,SDL_Surface *destination,int x, int y) 
{ 
    SDL_Rect offset; 
    offset.x = x; 
    offset.y = y; 

    SDL_BlitSurface(source, NULL, destination, &offset); 
} 


} //end class 

我的困惑是public:Button創造的價值如何被傳遞到void render我不能完全肯定我有這個權利,如果我有它的純因爲我仍然有點困惑。

回答

1

也許一個例子有助於:

#include <iostream> 
class Button 
{ 
private: 
    int m_x, m_y;   // coordinates of upper left corner of control 
    int m_width, m_height; // size of control 

public: 
    Button(int x, int y, int width, int height) : 
     //This is initialization list syntax. The other way works, 
     //but is almost always inferior. 
     m_x(x), m_y(y), m_width(width), m_height(height) 
    { 
    } 

    void MemberFunction() 
    { 
     std::cout << m_x << '\n'; 
     std::cout << m_y << '\n'; 
     //etc... use all the members. 
    } 
}; 


int main() { 
    //Construct a Button called `button`, 
    //passing 10,30,100,500 to the constructor 
    Button button(10,30,100,500); 
    //Call MemberFunction() on `button`. 
    //MemberFunction() implicitly has access 
    //to the m_x, m_y, m_width and m_height 
    //members of `button`. 
    button.MemberFunction(); 
} 
+0

謝謝你會擺弄它,應該幫助我更好地理解它:) – Sir

+0

我實際上得到一個錯誤,如果我這樣做:'按鈕btn_quit(10,30,100,500);' 它說'沒有構造函數的實例' – Sir

+0

啊我修正了我的錯誤這是我的錯誤:D謝謝! – Sir

1

在深入研究複雜的編程項目之前,您可能需要花一些時間學習C++。

要回答你的問題,在構造函數中初始化的變量(Button)是類實例的一部分。所以他們可以在任何類別的方法中使用,包括Render

+0

所以不是'offset.x = x'我會把'offset.x = m_x'? – Sir

+0

而不是以渲染的x和y作爲參數。 – abellina

+0

所以只有'void渲染(SDL_Surface * source,SDL_Surface * destination)' – Sir