是否可以在类中具有虚拟类声明
is it possible to have a virtual class declaration in a class?
我正在为个人项目中框架的各个组件设置一个接口,我突然想到了一些我认为可能对接口有用的东西。我的问题是这是否可能:
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;
}
相关文章:
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- 抽象类 A 由类 C 继承"through"类 B "intermediary"。如何声明虚拟功能?
- 有什么理由在没有继承的情况下声明一个虚拟方法
- C++如何使用虚拟基类型声明全局静态分配的变量
- 我们如何有证据表明,声明虚拟函数的类是2个字节,其中一个不超过一个未声明,而在子类中
- C 是纯虚拟函数,也是一个定义或仅声明
- 当声明了虚拟析构函数但没有实现时会发生什么情况
- 为什么我需要在子类中重新声明"虚拟"方法?[C++/多态性]
- 如何使用派生类中的虚拟函数,该函数在另一个具有基类参数的类中声明
- 不能声明Qwidget,因为虚拟函数是纯粹的
- 用派生类对象作为参数在基类中声明纯虚拟函数
- 在模板基类的虚拟函数中使用前向声明类,其中构造函数只需要前向声明
- 在基没有虚拟方法的派生类中声明虚拟方法是错误的吗
- 两次声明纯虚拟函数(在层次结构中的两个类中)是否完全合法
- 应该在所有继承级别还是仅在祖先级别声明虚拟函数
- 覆盖使用模板参数包扩展声明的虚拟方法时遇到问题
- 仅声明一个类公共虚拟
- 声明 RValue 方法(例如 void operation() 和 &;) 虚拟 C++1x )是否有意义
- 如何在不中断移动和复制构造函数的情况下声明虚拟析构函数
- 是否可以在类中具有虚拟类声明