不能在两个函数之间复制值

Cant copy value between two functions

本文关键字:函数 之间 复制 两个 不能      更新时间:2023-10-16

这是我的代码:

void Draw() {
        int x = 57;
        int y = 500;
        int temp = x;
        int colour;
        for (int i = 0; i <= 13; ++i){
            for (int j = 0; j <= 9; ++j){
                if (i % 2 == 0){
                    colour = 3;
                    }
                else colour = 4;
                DrawRectangle(x, y, 67, 30, colors[colour]);
                x = x + 67;
            }
            y = y - 30;
            x = temp;
        }

        DrawCircle(100, 100, 10, colors[2]);
        DrawRectangle(20, 0, 95, 12, colors[1]);

    }
    void Move(int key, int x, int y) {
        if (key == GLUT_KEY_LEFT) { // left arrow key is pressed
        }
        else if (key == GLUT_KEY_RIGHT) { // right arrow key is pressed

        }
        glutPostRedisplay(); // Redo- the drawing by calling
    }

这是我在一个类中的两个函数。我需要将x和y的值从Move()复制到Draw(),但Draw(()不接受任何参数,还有什么其他方法可以做到这一点。此外,如果有人需要完整的代码,他可以要求。

选项1

您可以将函数签名更改为Draw(int x, int y)。虽然您没有声明不能更改函数签名,但我猜这个选项是不可能的。

选项2

您指出这些是类的成员函数。因此,您需要在Move函数之外增加变量的范围。您可以通过使它们成为成员变量来实现这一点。例如:

class Foo
{
public:
    Foo() :
        mX(0),
        mY(0)
    {
        // Do nothing
    }
    void Draw()
    {
        ... code in here that uses mX and mY ...
    }
    void Move(int key, int x, int y)
    {
        mX = x;
        mY = y;
        ... other code ...
    }
private:
    // Class member variables accessible by all functions in the class
    int mX;
    int mY;
};

您可以使用全局变量,也可以将值作为参数发送。全局变量是在任何函数体外部声明的。

我不太明白为什么你不把参数传递给Draw()函数,因为你需要把变量传递给它。但这里有另一种方法可以做到这一点,而不是使用全局变量。

您可以创建一个具有这两种方法的新类,也许将其命名为Pen?然后向Pen类添加两个属性,更改函数Move()中的值,然后Draw()可以使用这些变量。

这比使用全局变量要好,因为你只想在这两个函数中使用它们,对吧?最好将每个变量都保持在它们应该存在的范围内

希望这会有所帮助。