2012-11-01 44 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