是否可以在类中拥有虚拟类声明?

Fat*_*sis 2 c++

我正在为个人项目中的框架的各种组件设置一个接口,我突然想到了一些我认为可能对接口有用的东西.我的问题是这是否可能:

class a
{
public:
    virtual class test = 0;

};

class b : public a
{
public:
    class test
    {
        public:
           int imember;
    };
};

class c : public a
{
public:
    class test
    {
    public:
           char cmember;  // just a different version of the class. within this class
    };
};
Run Code Online (Sandbox Code Playgroud)

声明需要在派生对象中定义的虚拟类或纯虚拟类,以便您可以执行以下操作:

int main()
{
    a * meh = new b();
    a * teh = new c();

    /* these would be two different objects, but have the same name, and still be able  
 to be referred to by an interface pointer in the same way.*/
    meh::test object1;    
    teh::test object2;

    delete meh;
    delete teh;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

msvc ++抛出了一堆语法错误,所以有没有办法做到这一点,我只是不写得对吗?

jua*_*nza 6

不,它无效.无论如何,C++没有虚拟类的概念.您可以通过仅使用纯虚方法保持指向某个类的指针来实现您想要的效果(尽管这不是必需的):

class ITest { /* full of pure virtual methods... maybe. */};

class a
{
public:
    virtual ITest* someFunctionName()=0 ;
private:
    ITest* test_;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以决定从a继承,为每个实现提供具体实现ITest,或者其他一些方法,例如,根据某些构造函数参数决定使用哪个实现.