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

时间:2012-04-20 06:11:20

标签: 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
    };
};

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

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 ++抛出了一堆语法错误,所以有没有办法做到这一点,我只是不写得对吗?

2 个答案:

答案 0 :(得分:6)

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

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

class a
{
public:
    virtual ITest* someFunctionName()=0 ;
private:
    ITest* test_;
};

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

答案 1 :(得分:0)

关键字“virtual”仅表示“table to dispatch function call。 你提出的不是语言的一部分。

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

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