在c ++中正确覆盖虚拟函数的问题,最终出现分段错误

问题描述 投票:1回答:1

i尝试覆盖功能,但最终出现分段错误。遵循了一些教程,现在我无法找到分段错误的起源。我使用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;
    }
c++ overriding header-files virtual
1个回答
0
投票

该问题与您的虚拟功能或替代无关。只是您使用的是不再存在的对象的地址。

在以下代码块中:

    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);行正试图取消对不再存在的对象的指针的引用,从而导致分段错误。

© www.soinside.com 2019 - 2024. All rights reserved.