2011-04-22 4 views
1

그래서 위치를 요청할 때 마지막으로 그려지는 공의 위치가 항상 문제가되는 것 같습니다. 객체를 선언 할 때 객체의 값이 올바르게 할당되지 않은 것처럼. 여기 다른 C++ 풀 공 객체 배열 문제

내가 방법 내부 변수를 선언하는 순간

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); 
} 

내 그리기 볼 방법 및 변수가 전달되는 방법

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); 
} 

지나가는 변수 나는 일할 수 없다.

01 23,516,
float ball::zPos 

그것은

float ball::GetZ() const { 
    return zPos; 
} 

를 검색하고되고 어떻게 나는 단순히 값

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 : I 객체들의 어레이의 크기를 증가하는 경우

#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을 읽고,이 같은 문제가있다.

기회가 누락되었습니다.

감사합니다.

답변

2

C++에서 배열 인덱싱은 0부터 시작하므로 ball TestBall[2];에 대한 유효한 인덱스는 TestBall[0]TestBall[1]입니다. TestBall[2]에 액세스하면 undefined behavior이 호출되고 이에 쓰면 확실히 메모리가 손상됩니다.

편집 :

xPos에서 yPos, zPos, DrawBall, UpdateBallPlaceballstatic를 분리합니다 (질문에 대한 응답에서 ball의 정의를 보여주기 위해 편집 중) 및 예상대로 동작해야한다 . 네임 스페이스 범위가 아닌 ball의 생성자에서 xPos, yPoszPos을 초기화해야합니다.

+0

내 코드를이 코드로 업데이트했습니다. 내 마음을 잃어버린 덕분에 문제는 여전히 지속됩니다. 댓글 주셔서 감사합니다! – Rodney

+0

@ 로드니 : 질문을 편집하여 '볼'의 클래스 정의를 표시 할 수 있습니까? – ildjarn

+0

@ildjarn 완료. 필요한 항목을 명확히하기 위해 .cpp와 .h를 포함했습니다. – Rodney