【问题标题】:another c++ pool ball object array issue另一个 C++ 池球对象数组问题
【发布时间】:2011-04-22 22:15:32
【问题描述】:

所以我遇到了一个问题,当我请求位置时,我似乎总是得到最后一个球的位置。好像在我声明对象时没有正确分配对象中的值。

这是我目前拥有的

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,如果我增加对象数组的大小,这也是同样的问题。

我很可能错过了一些简单的东西。

感谢您的宝贵时间。

【问题讨论】:

    标签: c++ arrays object


    【解决方案1】:

    在 C++ 中,数组索引是从 0 开始的,因此 ball TestBall[2]; 的有效索引是 TestBall[0]TestBall[1]。访问TestBall[2] 调用undefined behavior,写入它肯定会导致内存损坏。

    编辑:(针对正在编辑的问题以显示ball 的定义)

    xPosyPoszPosDrawBallUpdateBallUpdateBallPlaceball 中删除static,行为应该如您所愿。您需要在 ball 的构造函数中而不是在命名空间范围内初始化 xPosyPoszPos

    【讨论】:

    • 已经用这个更新了我的代码,感谢你的发现 - 让我忘记了,但问题仍然存在。感谢您的评论!
    • @Rodney : 你能编辑你的问题以显示ball的类定义吗?
    • @ildjarn 完成。包含 .cpp 和 .h 以阐明您可能需要的任何内容
    • @Rodney:答案已编辑。让所有班级成员static 是问题所在。
    • @ildjarn 非常感谢!非常感谢您的快速响应,我想我认为实际上使所有内容都变为静态是一种不好的做法 - 你能告诉我将它们声明为静态有什么问题吗?
    猜你喜欢
    • 2018-03-12
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 2021-05-14
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多