crosses initialization error in switch case statement

泪湿孤枕 提交于 2021-01-28 07:02:21

问题


I've got the following code:

Class A {
  public:
    A::A(const char* name):
      _name(name)
      {}
    virtual void doSomething();
  private:
    const char* _name;
}

Class B : public A {
  B::B(const char* name):
    A(name)
    {}
  void doSomething() {
    //do something
  }
}

So far so good, but I've experiencing an error crosses initialization of B* newB in the following code:

std::vector<A*> vectorOfAs;

switch (enumType) {
  case enum1 :  
    B* newB = new B("foobar");
    vectorOfAs.push_back(newB);
    break;
  case enum2 :
    C* newC = new C("barfoo");
    vectorOfAs.push_back(newC);
    break;
}

Why the error?

Some background: I want to store pointers of derived classes in a vector for easy searching/iterating. The names are unique so I can iterate through the vector and look for the pointer which points to the object with the right name. When calling a method from a pointed-to object, the inherited one should be called (//do something).

Edit: @François Andrieux: you're right. made (serious) typo. Changed Class B : public B to Class B: public A


回答1:


newB is in the scope of the switch statement, which makes it available in all switch cases, but won't be initialised in all of them. You should enclose each case in its own local scope (see this answer for more information):

switch (enumType) {
  case enum1 : 
  {
    B* newB = new B("foobar");
    vectorOfAs.push_back(newB);
    break;
  }
  case enum2 :
  {
    C* newC = new C("barfoo");
    vectorOfAs.push_back(newB);
    break;
  }
}

At which point you will get a compiler error in enum2 (thereby exposing a bug), in that you are pushing newB not newC, which is what I assume you intended:

switch (enumType) {
  case enum1 : 
  {
    B* newB = new B("foobar");
    vectorOfAs.push_back(newB);
    break;
  }
  case enum2 :
  {
    C* newC = new C("barfoo");
    vectorOfAs.push_back(newC); // <--
    break;
  }
}

This should work.



来源:https://stackoverflow.com/questions/44332447/crosses-initialization-error-in-switch-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!