C ++如何在switch语句中创建全局对象

时间:2019-02-25 02:26:50

标签: c++ object switch-statement

我写一个可以创建全局对象的switch语句时遇到问题。这是我要制作的简化代码。尝试引用超出范围的本地对象时出现错误。

#include <iostream>

class Class1
{
    int x = 0;
    void update(){x++;}
};

class Class2
{
    int x = 0;
    void update(){x++;}
};

//This tells the function which class I want to create my object as.
int classIndex = 0;

int main ()
{
    //This is how I would use a switch statement to create my object.
    switch(classIndex)
    {
        case 0: {Class1 *myObj = NULL; myObj = new Class1(); break;}
        case 1: {Class2 *myObj = NULL; myObj = new Class2(); break;}

        default: break;
    }

    //This is where I get the error "error: 'myObj' was not declared in this scope".
    myObj->update();

    std::cout << myObj->x << std::endl;

    return 0;
}

我不能在代码的顶部声明对象,因为我希望程序在运行时立即创建它们,而且我不知道要想先创建变量的对象是什么类。具体来说,我想稍后删除该对象并创建另一个具有相同名称但可能不同的类。这可能吗?

0 个答案:

没有答案