因未知原因而变化

时间:2013-11-01 14:57:14

标签: c++ variables

我有一个接一个地叫这两个方法;

m_Fence.Initialise(7);
m_Fence.CreateSquareFence();    

以下是他们的每一个细节;

void CFence::Initialise(int size)
{
    m_square_size = size;
}

void CFence::CreateSquareFence()
{
    int l_Vector_Pos = 0;

    //Set initial vector at origin and start of first fence
    CVector3f l_Fence_Position = CVector3f(0.0f,0.0f,0.0f);

    int l_side = 0; // Makes sure only 4 sides get created
    std::string bools[4] = {"plus_z", "plus_x", "minus_z", "minus_x"};
        //Draw 1st fence on 0 x-axis
        while(l_side < 4)
            {
                for(int i=0 ; i<=m_square_size ; i++)
                    {                   
                    //Find which direction it's going and set Fence position and add to vector
                    if(bools[l_side] == "plus_z" &&  i>0)
                        l_Fence_Position += CVector3f(0.0,0.0,beamLength);
                    else if(bools[l_side] == "plus_x" && i>0)
                        l_Fence_Position += CVector3f(beamLength,0.0,0.0);
                    else if(bools[l_side] == "minus_z" && i>0)
                        l_Fence_Position += CVector3f(0.0,0.0,-beamLength);
                    else if(bools[l_side] == "minus_x" && i>0)
                        l_Fence_Position += CVector3f(-beamLength,0.0,0.0);

                    fences[l_Vector_Pos].setPosition(l_Fence_Position);
                    l_Vector_Pos++;

                    //Increase this int to let it know what side we're creating
                    if(i == m_square_size) 
                        {
                            l_side++;
                    }
                }
            }
}

我通过了7,它最初将m_square_size变量更改为7,但是当我调用CreateSquareFence方法时,它最终变为0,我很难理解为什么。

1 个答案:

答案 0 :(得分:1)

将我的评论转化为答案

确保fences足够大,以便您不会超出界限并胜过相邻的内容(更常见的是,调用未定义的行为)。


另一方面,该代码似乎过于复杂。你可以像这样简化它:

void CFence::CreateSquareFence()
{
  int l_Vector_Pos = 0;

  //Set initial vector at origin and start of first fence
  CVector3f l_Fence_Position = CVector3f(0.0f, 0.0f, 0.0f);

  CVector3f offsets[4] = {
    CVector3f(0.0, 0.0, beamLength),
    CVector3f(beamLength, 0.0, 0.0),
    CVector3f(0.0, 0.0, -beamLength),
    CVector3f(-beamLength, 0.0, 0.0)
  };
  for (int l_side = 0; l_side < 4; ++l_side) {
    for (int i = 0; i <= m_square_size; ++i) {
      if (i>0)
        l_Fence_Position += offsets[l_side];
      fences[l_Vector_Pos].setPosition(l_Fence_Position);
      ++l_Vector_Pos;
    }
  }
}