调用虚函数覆盖导致分段错误

Calling override of virtual function is causing a segmentation fault

我正在尝试重写一个函数,但最终出现了分段错误。我遵循了一些教程,但现在找不到分段错误的根源。

我使用了 1 个头文件和 1 个 cpp 文件。 更新原因是我想制作多个命令,如打印和实例化不同的命令,并在不知道这是什么命令的情况下调用 Execute 方法。

这是在一个头文件中声明的:

  class Command{
    public:
     virtual int Execute(std::stack<NumericData>* stack)=0;
  };

  class Print : public Command{
    public:
     int Execute(std::stack<NumericData>* stack);
  };

这是一个cpp文件的实现:

 ... // inside some function
    std::stack<NumericData> stack;
    Command* command;
    if(1){                         // if is updated
        Print print;               // and reason for seg fault
        command=&print;            // without if it works
    }
    command->Execute(&stack); // <- segmentation fault
    ...

    int Command::Execute(std::stack<NumericData>* stack){
          printf("Execute parent\n");
          return 0; 
    }

    int Print::Execute(std::stack<NumericData>* stack){
          printf("Execute child\n");
          return 1;
    }

问题与您的虚函数或覆盖无关。很简单,您正在使用不再存在的对象的地址。

在以下代码块中:

    Command* command;
    if(1){                         // if is updated
        Print print;               // and reason for seg fault
        command=&print;            // without if it works
    }
    command->Execute(&stack); // <- segmentation fault

print 变量的生命周期仅限于其封闭范围({ ...})。因此,当您离开该范围时,您分配给 command 的地址不再有效,并且您的 command->Execute(&stack); 行试图取消引用指向不再存在的对象的指针,从而导致分段错误。