问题描述
你好:)我想问一下,是否可以做这样的事情:
Hello :) i would like to ask, if it's posible to make something like this:
我有基类(父类)A和其他三个类(子类)B C D在A类中,我有虚函数,没关系.但是如果我需要一个虚拟课怎么办?
i have base class (parent) A and three other classes (childs) B C Din class A, i have virtual functions, that's ok.but what if i need a virtual class ?
class A
{
public:
virtual int func1()=0;
virtual int func2()=0;
virtual class AB; // !!!!???
};
class B
{
public:
int func1();
int func2();
class AB
{
public:
....
};
};
类B C D与类B相同.现在,我想创建类实例,它应该自动将类重定向"到B或C D等功能的实例.
classes B C D are same as class B. Now, i would like to create class instance and it should automaticly "redirect" class to instance of B or C D etc like functions.
有可能吗?我希望您能理解:)非常感谢您的回答.
is it possible ? i hope, you understand :) Thank you very much for answer.
推荐答案
这从根本上是不可能的.在运行时确定虚拟函数调用.一个类在编译时更改程序的行为.除非运行时和编译时间是同一时间(即使用JIT或其他动态代码生成器),否则您无法在运行时确定编译时.在标准C ++中,这是不可能的.
This is fundamentally impossible. A virtual function call is determined at runtime. A class changes the behaviour of the program at compile-time. You can't make a compile-time determination at runtime unless runtime and compiletime are the same time, i.e. using a JIT or other dynamic code generators. In standard C++, this is impossible.
您可以做的是拥有一个基类AB,该基类具有一个虚函数,该虚函数创建一个可以从该基类继承的类,然后返回一个指向该基类的指针.
What you CAN do is have a base class AB, with a virtual function that creates a class that is guaranteed to inherit from this base class, and then return a pointer to that.
这篇关于抽象类中的虚拟类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!