2012-04-20 99 views
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++抛出我一堆语法错误,那么,有没有办法做到这一点,我只是不写对吗?

+0

你或许可以做到这一点使用*抽象类* – 2012-04-20 06:16:35

+0

听起来像一个XY问题什么是你真正的问题,因为不管它是什么,上面的代码是不是解决 – MSalters 2012-04-20 07:12:58

回答

6

不,它是无效的。无论如何,C++本身没有虚拟类的概念。你也许可以实现您拿着一个指向某一类纯虚函数想要的东西(虽然这不是一个要求):

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

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

然后你就可以决定从继承,让每一个具体的实施例如ITest的实现或者其他一些方法,例如基于某个构造器参数决定使用哪个实现。

+0

让人失望随之而来...。?。但是,谢谢你的建议,我想知道我正在努力的会得到合作足够的灵活性,而不必为了得到这个:/。我敢肯定,我可以找到与虚拟课程不同的方式。任何人都知道为什么这*不是*功能? – FatalCatharsis 2012-04-20 06:29:22

+0

@FatalCatharsis:粗略地说,''''范围运算符在左边有一个类(或名称空间),而'.'运算符在左边有一个值(对象,引用,表达式等)。 'meh :: test'将'::'应用于指针'meh'。另外,C++是强类型的。表达式'meh :: test'的静态类型必须在编译时设置。可能你可以有一个动态类型派生出来,Liskov Substitution允许这样做,但是它的机制完全不清楚。 – MSalters 2012-04-20 07:12:03

0

关键字“虚拟”仅仅意味着“表派遣函数调用。 你所提出的不是语言的一部分。

但是你可以用另一种方式接近它,通过链接对象创建适当的虚拟电话:

#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; 
} 
相关问题