调用虚拟函数的覆盖导致分段故障。

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

我正想覆盖一个函数,但最后却出现了分段故障。我遵循了一些教程,现在我无法找到分段故障的根源。

我使用了一个头文件和一个cpp文件。更新 原因是,我想做多个命令,如打印和实例化不同的命令,并调用执行方法,而不知道到底是什么命令。

这是在一个头文件声明。

  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个回答
2
投票

这个问题与你的虚拟函数无关,也与覆盖无关。只是你使用了一个已经不存在的对象的地址。

在下面的代码块中

    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.