super-class 的方法调用 WHEN super 具有 str attr + sub 的实例在循环中创建 + 实例作为 super 的指针存储在向量中

method of super-class called WHEN super has a str attr + instance of sub is created in a loop + instance is stored in a vector as a pointers of super

合并多个条件时,我无法访问子class'实例的方法:

看起来像这样:

class Parent
{
  public :
    string name;
    virtual void myMethod() = 0;
};

class Child : public Parent
{
  public :
    void myMethod();
};

void Child::myMethod()
{
  cout << "I'm a child";
}

int main(void)
{
  vector<Parent*> children;

  for(unsigned int i = 0 ; i < 1; i++ )
  {
    Child c;

    children.push_back(&c);
  }

  (*children[0]).myMethod();
}

在那种情况下,代码结束时出现错误:“调用了纯虚方法 在没有活动异常的情况下终止调用”。我猜它正在尝试访问虚拟的 'Parent::myMethod' 并因此失败。为了避免这个问题,我可以: - 删除超class的属性'name' - 更改该属性的类型(例如 int) - 从 for 循环外部将元素附加到向量。

我只是想不通在那个特定情况下发生了什么...

这里只有一个 "condition" 重要:当 Child c; 超出范围时,您推入向量的指针指向垃圾:

{
  Child c;                   // this object lives only in this scope !!

  children.push_back(&c);    // <-- &c is fine here
}                            // <-- already here it is not !

(*children[0]).myMethod();   // ***BOOM***

也许您的印象是它是出现错误的特定条件组合,但这只是因为取消引用无效指针是未定义的行为,所以有时它看起来好像有效,但实际上它永远不正确。