c – 多于1个派生类对象的地址?

前端之家收集整理的这篇文章主要介绍了c – 多于1个派生类对象的地址?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在“有效C”(第3版,第118页)的第27项中,Scott Meyers说:
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).

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

猜猜这里有一些误会.有人可以做一些澄清吗?这可能与C编译器中多态性的实现有关吗?

解决方法

去尝试一下:
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子对象.

原文链接:https://www.f2er.com/c/116218.html

猜你在找的C&C++相关文章