所以我遇到了一个问题,当我请求位置时,我似乎总是得到最后一个球的位置。就好像我在声明对象时没有正确分配对象中的值一样。
这是我目前的情况
ball TestBall[2];
在方法中声明变量
void ball::Placeball() {
//TEMP TEST
TestBall[1].DrawBall(5,0.15,10,3,10);
//TEMP TEST
TestBall[2].DrawBall(5,0.15,10,3,30);
}
我的 Draw Ball 方法以及如何传递变量
void ball::DrawBall(float radius, float mass, float x, float y, float z) {
xPos = x;
yPos = y;
zPos = z;
GLUquadricObj *quadratic;
quadratic = gluNewQuadric();
glPolygonMode(GL_FRONT,GL_FILL);
glPolygonMode(GL_BACK,GL_FILL);
gluQuadricNormals(quadratic,GLU_SMOOTH);
glTranslatef(x,y,z);
gluSphere(quadratic,radius,20,20);
glTranslatef(-x,-y,-z);
}
我无法正常工作的传递变量
float ball::zPos
以及它是如何被检索的
float ball::GetZ() const {
return zPos;
}
然后我如何简单地尝试获取值(value)
cout << TestBall[1].GetZ() << endl; //should be 10
cout << TestBall[2].GetZ() << endl; //should be 30
ball.cpp:
float ball::xPos = 0;
float ball::yPos = 0;
float ball::zPos = 0;
ball::ball() { };
void ball::DrawBall(float radius, float mass, float x, float y, float z) {
xPos = x;
yPos = y;
zPos = z;
GLUquadricObj *quadratic;
quadratic = gluNewQuadric();
glPolygonMode(GL_FRONT,GL_FILL);
glPolygonMode(GL_BACK,GL_FILL);
gluQuadricNormals(quadratic,GLU_SMOOTH);
glTranslatef(x,y,z);
gluSphere(quadratic,radius,20,20);
glTranslatef(-x,-y,-z);
}
float ball::GetX() const {
return xPos;
}
float ball::GetY() const {
return yPos;
}
float ball::GetZ() const {
return zPos;
}
ball.h:
#pragma once
class ball
{
private:
static float xPos;
static float yPos;
static float zPos;
public:
ball();
ball(float radius, float mass, float x, float y, float z){};
~ball(){};
static void DrawBall(float radius, float mass, float x, float y, float z);
static void UpdateBall(float speedx, float speedz);
static void Placeball();
float GetX() const;
float GetY() const;
float GetZ() const;
};
两个值都是 30,如果我增加对象数组的大小,这也是同样的问题。
很可能是我遗漏了一些简单的东西。
感谢您的宝贵时间。
最佳答案
在 C++ 中,数组索引是从 0 开始的,因此 ball TestBall[2];
的有效索引是 TestBall[0]
和 TestBall[1]
.正在访问 TestBall[2]
调用 undefined behavior ,并且写入它肯定会导致内存损坏。
编辑:(针对正在编辑的问题以显示 ball
的定义)
删除 static
来自 xPos
, yPos
, zPos
, DrawBall
, UpdateBall
, 和 Placeball
并且行为应该如您所料。您需要初始化 xPos
, yPos
, 和 zPos
在 ball
的构造函数而不是在命名空间范围内。
关于c++ - 另一个 C++ 池球对象数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760592/