名为WHEN的超类的方法,其中超有一个strattr +在循环中创建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

查看:217
本文介绍了名为WHEN的超类的方法,其中超有一个strattr +在循环中创建sub的实例+实例作为super的指针存储在向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当多个条件合并时,我无法到达子类实例的方法:

I can't reach a method of a sub-class' instance when several conditions are merged :

  • 超类中有一个string类型的属性.
  • 实例已循环创建
  • 该实例存储在带有超类指针的向量中

它看起来像这样:

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',因此失败.为了避免该问题,我可以: -删除超类的属性名称" -更改该属性的类型(例如,将其更改为int) -从for循环的外部将元素附加到向量.

In that case the code over with an error : "pure virtual method called terminate called without an active exception". I guess that it's trying to access to 'Parent::myMethod' that is virtual and so fail. To avoid that issue I can : - Remove the attribute 'name' of the super-class - Change the type of that attribute (to int for exemple) - Append the elements to the vector from outside of the for loop.

我只是不知道在这种情况下发生了什么...

I just can't figure what is going on in that specific case...

推荐答案

这里只有一个条件"很重要:当Child c;超出范围时,在向量中压入的指针指向垃圾:

There is only one "condition" that matters here: the pointers you push in the vector point to garbage when Child c; goes out of scope:

{
  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***

也许您会感觉是错误的特定条件组合,但这仅仅是因为取消引用无效的指针是未定义的行为,因此有时看起来确实可行,而实际上却永远是不正确的.

Maybe you got the impression that it is a specific combination of conditions to get the error, but thats just because dereferencing an invalid pointer is undefined behaviour, so sometimes it may look like it worked when actually it is never correct.

这篇关于名为WHEN的超类的方法,其中超有一个strattr +在循环中创建sub的实例+实例作为super的指针存储在向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆