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

is it possible to have a virtual class declaration in a class?

本文关键字:虚拟 声明 是否      更新时间:2023-10-16

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

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

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

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

msvc++给我抛出了一堆语法错误,那么有没有办法做到这一点,而我只是写得不对?

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

class ITest { /* full of pure virtual methods... maybe. */};
class a
{
public:
    virtual ITest* someFunctionName()=0 ;
private:
    ITest* test_;
};

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

关键字"virtual"仅表示"用于调度函数调用的表"。你提出的不是语言的一部分。

但是您可以通过另一种方式来处理它,通过将对象创建链接到适当的虚拟调用:

#include <iostream>
using namespace std;

class a
{
public:
    class test
    {
    public:
        virtual ~test() {} ///< required to have polimorphic behavior
        virtual void hello() const =0;
    };
    virtual test* create_test()=0;
};

class b: public a
{
public:
    class test_b: public a::test
    {
        virtual void hello() const 
        { cout << "this is test_b at " << this << endl; }
    };
    virtual test* create_test() 
    { return new test_b; }
};
class c: public a
{
public:
    class test_c: public a::test
    {
        virtual void hello() const 
        { cout << "this is test_c at " << this << endl; }
    };
    virtual test* create_test() 
    { return new test_c; }
};
int main()
{
    a* pa1 = new b;
    a* pa2 =  new c;
    a::test* p1 = pa1->create_test();
    a::test* p2 = pa2->create_test();
    p1->hello();
    p2->hello();
    delete p2; delete p1;
    delete pa2; delete pa1;
}