一个以上的地址为派生类对象? [英] More than 1 address for derived class object?

查看:102
本文介绍了一个以上的地址为派生类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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




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

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.

这最后一个示例演示了单个对象(例如, Derived )的对象可能有多于一个地址(例如,由 Base * 指针指向的地址及其由 Derived * pointer)。

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?

推荐答案

只要尝试一下:

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;
}

B1 子对象具有与 B2 子对象相同的
地址。

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

这篇关于一个以上的地址为派生类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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