2011-04-22 22 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); 
} 

的傳遞變量我無法上班

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

#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,寫入它肯定會導致內存損壞。

編輯:(在回答這個問題被編輯以示ball的定義)

xPos刪除staticyPoszPosDrawBallUpdateBallPlaceball和行爲應該像您期望。您需要在ball的構造函數中初始化xPos,yPoszPos,而不是在名稱空間範圍內。

+0

已經更新了我的代碼,感謝您的發現 - 我放棄了自己的想法,但問題仍然存在。感謝評論! – Rodney 2011-04-22 22:26:09

+0

@Rodney:你可以編輯你的問題來顯示'ball'的類定義嗎? – ildjarn 2011-04-22 22:29:44

+0

@ildjarn完成。包括.cpp和.h來澄清你可能需要的任何東西 – Rodney 2011-04-22 22:35:59