不能在两个函数之间复制值
Cant copy value between two functions
这是我的代码:
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()
可以使用这些变量。
这比使用全局变量要好,因为你只想在这两个函数中使用它们,对吧?最好将每个变量都保持在它们应该存在的范围内
希望这会有所帮助。
相关文章:
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 填充上编译器生成的复制构造函数之间的不一致
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 如何在"push_*()"和"emplace_*()"函数之间进行选择?
- 仅具有运算符()的结构和普通函数之间的实际区别
- 当两者都调用时,删除和析构函数之间的区别?
- Release() 和析构函数之间的区别?
- 调用 "project" 函数和调用 DLL 函数之间的区别
- C++模板和非模板函数之间的重载解析
- std::shared_ptr 和 std::unique_ptr 构造函数之间的不对称
- C++ 和 Lua 函数之间的交互与 3D 矢量参数
- 在结构函数之间传递文件路径 C++ 编辑:修复LNK2019错误
- 在C++同名的顶级函数之间进行选择
- 在成员函数之间传递const变量为数组的索引
- Helgrind 报告了使用 Singleton 及其构造函数之间可能存在的竞争
- 函数模板和函数之间奇怪的不一致"normal"
- 在c#和c函数之间传递值和指针
- 在C++中调用 malloc() 与"operator new"函数之间的实现差异
- 在函数之间传递相同的数组
- C++编译错误是由于使用 std::move 时运动构造函数与其他非运动构造函数之间的冲突