在switch case语句中遇到初始化错误 [英] crosses initialization error in switch case statement

查看:129
本文介绍了在switch case语句中遇到初始化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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
  }
}

到目前为止,还不错,但是在以下代码中,我遇到了错误 B * newB的初始化交叉:

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;
}

为什么会出错?

一些背景:我想将派生类的指针存储在向量中以便于搜索/迭代.名称是唯一的,因此我可以遍历向量并寻找指向具有正确名称的对象的指针.从指向对象调用方法时,应调用继承的方法(//执行某些操作).

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).

@FrançoisAndrieux:您是对的.做出(严重)错别字.将 Class B:公共B 更改为 Class B:公共A

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

推荐答案

newB 在switch语句的范围内,这使其在所有switch情况下都可用,但不会在他们都是.您应该将每种情况都包含在其自己的本地范围内(有关更多信息,请参见此答案):

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;
  }
}

这时,您将在enum2中遇到编译器错误(从而暴露了一个错误),因为您推送的是newB而不是newC,这是我假设的目的:

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;
  }
}

这应该有效.

这篇关于在switch case语句中遇到初始化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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