2

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

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

4

2 回答 2

6

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

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

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

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

于 2012-04-20T06:12:39.313 回答
0

关键字“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;
}
于 2012-04-20T06:30:07.173 回答