c++ - 与类中的变量混淆

标签 c++ sdl

我对类(class)有点困惑,希望有人能解释一下。

我正在开设一个类(class),为游戏菜单创建按钮。有四个变量:

int m_x int m_y 整数宽度 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 我不完全确定我做对了,如果我到目前为止运气不错,因为我仍然有点困惑。

最佳答案

也许一个例子会有所帮助:

#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();
}

关于c++ - 与类中的变量混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13170339/

相关文章:

c++ - OpenGL 中的乱序 Z 缓冲区

c++ - 如何同时使用 Qt 和 SDL?

c++ - Direct2D 中的多线程

c++ - opencv加载图像的两种方式有什么不同?

C++/SDL 内存管理

c - 使用sdl2-ttf打开系统字体

c++ - 将 SDL_Surface Blit 到另一个 SDL_Surface 并应用颜色键

c# - 如何制作 C# DLL COM InterOp 方法的 C++ 包装器?

c++ - 如何测试主存访问时间?

c# - 将数据从 C++ 传递到 C# 的最有效方法