繁体   English   中英

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

[英]Why is the std::vector not giving any outputs in c++

我不明白为什么,但在我将 class 指针放入数组后,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");
}

这是我建议养成对所有if语句使用花括号的习惯的原因之一,即使是那些位于一行中的语句。

问题线路:

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

让我们添加一些换行符以更清楚地了解正在发生的事情

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

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

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

但是,你想要的需要这样写:

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

if还要检查_currentState ,您在下一个问题中也会遇到同样的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM