为什么 std::vector 在 C++ 中没有给出任何输出

all*_*e50 0 c++ pointers class stdvector

我不明白为什么,但在我将类指针放入数组后, std::vector 没有给出任何内容。

// runs at start
void States::AssignState(GameState* state) {
    _nextVacentState++;
    _states.push_back(state);
}

// executes in a loop
void States::ExecuteCurrentState() {
    // protection incase there is nothing in the array or the current state is not grater than the size of the array (not the problem after i nerrowed the problem down)
    if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; // there is no states
    if (_currentState >= _states.size() - 1) std::cout << "Error: Current State is grater than all possable states" << std::endl; return;
    
    // The program just freezes at this and i can figure out why
    _states[0]->tick();
    std::printf("S");
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*son 7

if这是我建议养成对所有语句(甚至是位于一行的语句)使用大括号的习惯的原因之一。

问题线:

if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return;
Run Code Online (Sandbox Code Playgroud)

让我们添加一些换行符以使发生的事情更清楚

if (_nextVacentState == 0) 
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
  return;
Run Code Online (Sandbox Code Playgroud)

return语句将无条件执行,因为只有后面的第一个语句if(_nextVacentState==0)实际上是if. 所以编译器执行它就好像它是这样写的:

if (_nextVacentState == 0)
{
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
}
return;
Run Code Online (Sandbox Code Playgroud)

但是,您想要的内容需要这样写:

if (_nextVacentState == 0) 
{
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
  return;
}
Run Code Online (Sandbox Code Playgroud)

您在下一次if检查中_currentState也遇到同样的问题。