是否可以通过增加基类指针(C++)来创建指向继承类的指针?
根据我阅读的内容,看来派生对象的内存是通过基类依次制作的,其所有数据首先制作,然后立即在继承树下进行以下类。因此,如果我制作一个等于新派生的类对象的基类指针,然后以一个对象进行递增(实际上会将基类的大小添加到地址中),那么我会到达派生的类吗?如果是这样,我可以以这种方式访问派生类的数据吗?
Based on what I’ve read, it seems the memory for derived objects is made sequentially with the base class and all its data made first and then immediately followed by the following classes down the inheritance tree. So if I make a base class pointer that is equal to a new derived class object, and then increment it by one(which will actually add the size of the base class to the address), then will I arrive at the derived class? If so, can I then access the derived class’s data in this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,否。在最简单的情况下,在大多数情况下,它将起作用:
对于单个继承,通常您会从大多数编译器中看到的东西(尽管我非常担心实际上依靠生产代码!)
但是,可悲的是事情并不总是那么简单!在C ++中,我们通常具有多个继承,虚拟继承,抽象基础类别以及所有这些善良的位。因此,这是一种绝对不起作用的场景!
但是,有更安全的方法来处理起伏(例如Dynamic_cast或您自己的RTTI系统)。您可能想使用这些:)
Yes, and no. In the very simplest case it will work in most cases:
For single inheritance, that is typically what you'll see from most compilers (although I'd be very worried actually relying on that in production code!)
However, sadly things aren't always that simple! In C++ we often have multiple inheritance, virtual inheritance, abstract base classes and all those bits of goodness. So here is a scenario where it would absolutely not work!
There are however far safer approaches to handling upcasting (e.g. dynamic_cast, or your own RTTI system). You probably will want to be using those :)