派生类对象的地址超过 1 个?

More than 1 address for derived class object?(派生类对象的地址超过 1 个?)
本文介绍了派生类对象的地址超过 1 个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Effective C++"(第 3 版,第 118 页)的第 27 项中,Scott Meyers 说:

class Base { ... };类派生:公共基础{...};导出d;基数 *pb = &d;

<块引用>

这里我们只是创建了一个指向派生类对象的基类指针,但有时这两个指针并不相同.在这种情况下,会在运行时对 Derived* 指针应用偏移量,以获得正确的 Base* 指针值.

最后一个例子演示了单个对象(例如,Derived 类型的对象)可能有多个地址(例如,当 Base* 指针及其地址,当由 Derived* 指针指向时).

这里有点难以理解.我知道指向基类的指针可以在运行时指向派生类的对象,这称为多态或动态绑定.但是派生类对象在内存中真的不止1个地址吗?

我想我在这里有一些误解.有人可以澄清一下吗?可能这与C++编译器中多态的实现方式有关?

解决方案

试试吧:

B1 类{诠释我;};B2级{诠释我;};D类:公共B1,公共B2{诠释我;};整数主要的(){爸爸;std::cout <<&aD<<标准::endl;std::cout <<static_cast<B1*>(&aD)<<标准::endl;std::cout <<static_cast<B2*>(&aD)<<标准::endl;返回0;}

B1 子对象不可能有相同的地址作为 B2 子对象.

In Item 27 of "Effective C++" (3rd Edition, Page 118), Scott Meyers said:

class Base { ... };
class Derived: public Base { ... };
Derived d;
Base *pb = &d;

Here we're just creating a base class pointer to a derived class object, but sometimes, the two pointers will not be the same. When that's the case, an offset is applied at runtime to the Derived* pointer to get the correct Base* pointer value.

This last example demonstrates that a single object (e.g., an object of type Derived) might have more than one address (e.g., its address when pointed to by a Base* pointer and its address when pointed to by a Derived* pointer).

Here is a bit hard to understand. I know that a pointer to the base class can point to an object of the derived class at runtime, this is called polymorphism or dynamic binding. But does the derived class object really have more than 1 address in the memory?

Guess I have some misunderstanding here. Could someone give some clarification? Maybe this has something to do with how polymorphism is implemented in the C++ compiler?

解决方案

Just try it:

class B1
{
    int i;
};

class B2
{
    int i;
};

class D : public B1, public B2
{
    int i;
};

int
main()
{
    D aD;
    std::cout << &aD << std::endl;
    std::cout << static_cast<B1*>( &aD ) << std::endl;
    std::cout << static_cast<B2*>( &aD ) << std::endl;
    return 0;
}

There's no possible way for the B1 sub-object to have the same address as the B2 sub-object.

这篇关于派生类对象的地址超过 1 个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Polymorphic copy-constructor with type conversion(具有类型转换的多态复制构造函数)
Cast to a Child(铸造给孩子)
How to use virtual functions to achieve a polymorphic behavior in C++?(如何使用虚函数在 C++ 中实现多态行为?)
Polymorphism is not working with function return values of same data type (Base and Inherited class)(多态性不适用于相同数据类型(基类和继承类)的函数返回值)
Size of class with virtual function adds extra 4 bytes(具有虚函数的类的大小增加了额外的 4 个字节)
Right design pattern to deal with polymorphic collections of objects(正确的设计模式来处理对象的多态集合)