无法复制两个函数之间的值

时间:2015-03-28 05:04:32

标签: c++ syntax

所以这是我的代码:

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
    }

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

3 个答案:

答案 0 :(得分:2)

选项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;
};

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

这比使用全局变量更好,因为你只想在这两个函数中使用它们吗?最好将每个变量保留在它们应该的范围内。

希望这会有所帮助。

相关问题