创建虚拟指针 [英] Virtual pointer is created

查看:69
本文介绍了创建虚拟指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



在C ++中,如何根据我们在main中创建的基类或派生类或对象中的虚函数生成VPointer。



示例:



Hi All,

In C++ , how VPointer is generated as per virtual function in base class or derived class or object we create in main.

Example:

class Shape
{
public:
Shape(){}
~Shape(){}
virtual void Draw(){}
virtual void Draw1(){}

};

class Circle : public Shape
{
public:
Circle(){}
~Circle(){}
void Draw(){}

};

int main()
{
}



创建或生成了多少VPTR?


how many VPTR is created or generated ?

推荐答案

它是否是OOP理论的赋值?首先,您需要了解何时生成虚拟方法表以及这些表如何映射到类型及其成员上。如果您了解VMT(vtable)的工作原理,您将能够计算这些指针(在实践中无意义的业务,但可能是一个公平的设备来检查您的理解)。例如,在阅读并理解了本文之后:

http://en.wikipedia.org/wiki / Virtual_method_table [ ^ ]。



祝你好运,

-SA
Is it an assignment on OOP theory? First of all, you need to understand when the virtual method table is generated and how are those tables mapped on the types and their members. You will be able to count those pointers (pointless business in practice, but might be a fair device to check up your understanding), if you learn how VMT (vtable) works. For example, after reading and understanding of this article:
http://en.wikipedia.org/wiki/Virtual_method_table[^].

Good luck,
—SA


基本上,需要VFT才能解析功能在运行时调用。因此,每当一个类将至少一个方法定义为虚拟,或者从具有在任何地方覆盖的虚方法的基类继承时,该类可能需要一个VFT。



但是要明白,需要VFT的是,而不是每个类的实例!然后,该实例将只包含一个指向该类的正确VFT的附加指针。因此,如果你有三个实例 Circle circle1,circle2,circle3; ,每个实例都有一个指向 Circle <的唯一VFT的指针/ code> class。如果您然后定义另一个派生类 Square ,该类的实例将包含指向 Square VFT的VFT指针。然后你可以将 Circle Square 存储在一个集合中,作为 Shape 指针,并在所有上调用虚函数。这样做将引用存储的VFT指针以获取每个实例的正确函数指针。
Basically, VFTs are needed to resolve function calls at runtime. Therefore, every time a class defines at least one method as virtual, or inherits from a base class with virtual methods that are overriden anywhere, that class will probably need a VFT.

Understand however, that it is the class that needs the VFT, not each instance of the class! The instance will then only contain one additional pointer that points to the correct VFT for that class. So if you have three instances Circle circle1, circle2, circle3;, each of them will have one pointer to the one and only VFT of the Circle class. If you then define another derived class Square, instances of that class will contain VFT pointers to the Square VFT. Then you can store Circles and Squares in a collection as Shape pointers, and call virtual functions on all. Doing so will reference the stored VFT pointer to obtain the correct function pointer for each instance.


这篇关于创建虚拟指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆