创建未知类的对象(两个继承的类)

Pau*_*aul 1 c++ inheritance class

我有以下课程:

class A {
    void commonFunction() = 0;
}

class Aa: public A {
    //Some stuff...
}

class Ab: public A {
    //Some stuff...
}
Run Code Online (Sandbox Code Playgroud)

根据用户输入,我想创建Aa或Ab的对象.我的imidiate想法是这样的:

A object;
if (/*Test*/) {
    Aa object;
} else {
    Ab object;
}
Run Code Online (Sandbox Code Playgroud)

但是编译器给了我:

error: cannot declare variable ‘object’ to be of abstract type ‘A’
because the following virtual functions are pure within ‘A’:
//The functions...
Run Code Online (Sandbox Code Playgroud)

有没有好办法解决这个问题?

Cor*_*sky 7

使用指针:

A *object;
if (/*Test*/) {
    object = new Aa();
} else {
    object = new Ab();
}
Run Code Online (Sandbox Code Playgroud)