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;
}
该问题与您的虚拟功能或替代无关。只是您使用的是不再存在的对象的地址。
在以下代码块中:
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);
行正试图取消对不再存在的对象的指针的引用,从而导致分段错误。