为什么此子类代码会导致运行时错误

Why does this subclass code cause a runtime error?

本文关键字:运行时错误 代码 子类 为什么      更新时间:2023-10-16

我有一个我使用X扩展的基类AA内部还有另一个类B。似乎没有定义虚拟方法,但我不明白为什么?

class A {
 public:
  class B {public: bool value;};
  A() {}
  B b_;
  void DoStuff(B& b);
 private:
  virtual void DoStuffImpl(B& b) = 0;
};
class X : public A {
 public:
  X() {}
  void Trigger();
 private:
  virtual void DoStuffImpl(B& b);
};
void A::DoStuff(B& b) {
     DoStuffImpl(b);
}
void X::Trigger() {
    DoStuff(b_);
}
void X::DoStuffImpl(B& b) {
    b.value = true;
}
int main(){
    X x;
    x.Trigger();
    return x.b_.value;
}

P.S。之所以出现,是因为我的代码有不同的问题,但是我什至无法使这个玩具示例起作用,所以现在我让我感到好奇了....

这是上述代码的链接,该链接正在编译和无法运行:http://ideone.com/mbj1kg

它运行良好。IDEONE报告了一个"运行时错误",其退出代码为1,因为您从main返回1。通常认为非零返回代码是故障。

如果您评论return x.b_.value行并将其替换为return 0,则一切都很好。

您可能已经在其中放了一些std::cout行以查看发生了什么,并查看程序有效!:D