another c++ pool ball object array issue
So I'm having a problem where I always seem to be getting the location of the last ball drawn when I'm requesting the location. As though the values in the objects are not being assigned properly when I'm declaring the object.
Here is what I have at the moment
ball TestBall[2];
Declaring variables inside a method
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);
}
My Draw Ball Method and how the variable is being passed
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);
}
The passing variable I can't get to work
float ball::zPos
and how it's being retrieved
float ball::GetZ() const {
return zPos;
}
And then how I'm simply trying to get the value
cout << TestBall[1].GetZ() << endl; //should be 10
cout << TestBall[2].GetZ() &l开发者_如何学Ct;< 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;
};
Both values read 30, this is the same problem if I increase the size of the array of objects.
Chances are it is something simple I'm missing.
Thanks for your time.
In C++, array indexing is 0-based, so valid indices for ball TestBall[2];
are TestBall[0]
and TestBall[1]
. Accessing TestBall[2]
invokes undefined behavior, and writing to it certainly causes memory corruption.
EDIT: (In response to the question being edited to show ball
's definition)
Remove static
from xPos
, yPos
, zPos
, DrawBall
, UpdateBall
, and Placeball
and the behavior should be as you expect. You'll need to initialize xPos
, yPos
, and zPos
in ball
's constructor instead of at namespace scope.
精彩评论