类属性值不正确

Class attribute incorrect value C++

本文关键字:不正确 属性      更新时间:2023-10-16

EDIT: 要初始化位置数组m_pos[3],我在构造函数中将所有值设置为0,然后我从主函数中调用另一个名为SetPos()的函数,该函数仅设置行星在3D地图中的位置:

void SetPos(float x, float z);
void Planet::SetPos(float x, float z)
{
  m_pos[0]=x;
  m_pos[1]=0;
  m_pos[2]=y;
}
因此,构造函数的形式为:
Planet::Planet()
{
  m_pos[0]=0;
m_pos[1]=0;
m_pos[2]=0;
}

这样做不好吗?(根据需要,我不能直接通过构造函数设置位置)。

原始:

我创建了一个叫做Planet的类,它控制了map中的一系列行星(Planet对象)。每个物体都有一个array pos[3],用于存储必须绘制行星的坐标。

行星还拥有一个称为DrawConnections()的函数,该函数负责绘制代表实际行星与其他行星之间连接的线条。一个行星所连接的行星存储在一个向量std::vector<Planet> connections中。

由于属性被封装,在Planet类中有一个函数返回行星的位置,称为GetPos(float* pos),其中*pos是一个指针,指向一个能够存储行星位置的数组。

首先,这些是Planet.h文件中的原型和变量声明:

public:
void DrawConnections(float radius);
void GetPos(float* position);
private:
float m_pos[3];
std::vector<Planet> m_connection;

来自Planet.cpp的DrawConnections()函数如下所示:

void Planet::DrawConnections(float radius) //parameter radius controls width of lines
{
float position[3]={0.0f,0.0f,0.0f};   //array storing the position of the planets
                                      //which we are connecting to
//various OpenGl calls go here
glBegin(GL_LINES);                    //begins drawing the lines
for(int i=0;i<m_connection.size();i++)  //for each planet we are connected to, draw a
                                        //line
{
    glVertex3f(m_pos[0],m_pos[1],m_pos[2]);  //draws the first point of the line in the 
                                           //actual planet
    m_connection[i].GetPos(position);    //Gets the position of the planet we connect to
    glVertex3f(position[0],position[1],position[2]);  //draws the second point of the
                                                      //in the planet we connect to
}
glEnd();                                             //ends drawing

//some other OpenGl calls
}

来自Planet.cpp的GetPos()函数如下所示:

void Planet::GetPos(float* position)
{
    position[0]=m_pos[0];                  //copies the data from the position array to 
    position[1]=m_pos[1];                  //the given pointer
    position[2]=m_pos[2];
}

任何行星都有x坐标,没有z坐标,也没有0坐标。每一个都有一组(x,y,z)坐标,x和z总是不等于0。

然而,对GetPos()的一些调用返回x和z等于0,而其他调用正常工作。

这导致许多从行星到屏幕左下角的线,没有表示任何连接。从我所发现的,我认为问题是在GetPos()。然而,其他类似的绘图函数也使用GetPos(),当它们在DrawConnection()函数之前被调用时工作完美,但是当它们被调用时,一旦DrawConnections()被调用,似乎就会受到影响。这就好像一个人在调用时修改了位置数组的值,从而干扰了其他所有必须与位置相关的东西,包括她自己。

作为附加信息,我正在使用代码块和MinGW GNU GCC编译器。我很感激你给我的任何帮助。

为什么不呢?

public:
void DrawConnections(float radius);
const std::vector<float>& GetPos() const {return m_pos;};
private:
std::vector<float> m_pos;
std::vector<Planet> m_connection;