在“有效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 correctBase*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 aBase*pointer and its address when pointed to by aDerived*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子对象.