派生类对象的地址超过 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 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).
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.
相关文章