[英]what does compiler do when new an object and assign the address of the created object to its base class pointer
Example 3 :(page 377) 例3 :(第377页)
class A {virtual void f();};
class B {virtual void f(); virtual void g();};
class C: A, B {void f();};
A* pa = new C;
B* pb = new C;
C* pc = new C;
pa->f();
pb->f();
pc->f();
pc->g()
(1) In Multiple inheritance for C++ , Bjarne wrote: On entry to C::f
, the this
pointer must point to the beginning of the C
object (and not to the B
part). (1)在C ++的多重继承中 ,Bjarne写道:在进入C::f
, this
指针必须指向C
对象的开头(而不是B
部分)。 However, it is not in general known at compile time that the B
pointed to by pb
is part of a C
so the compiler cannot subtract the constant delta(B)
. 但是,在编译时通常不知道pb
指向的B
是C
一部分,因此编译器无法减去常数delta(B)
。
Why does the compiler not know that B
pointed to by pb
is part of a C
at compile time? 为什么编译器在编译时不知道pb
指向的B
是C
一部分? Based on my understanding, B
pointed to by pb
is definitely a part of C
since we new C
and C
inherits from B
! 根据我的理解, pb
指向的B
肯定是C
的一部分,因为我们new C
和C
继承自B
!
What about B* pb = new B;
B* pb = new B;
? ? does the compile know B
pointed to by pb is a standlone object? 编译器是否知道pb指向的B
是独立对象?
Let's make a few minor changes to your code: 让我们对代码进行一些小的更改:
struct A {virtual void f() {}};
struct B {virtual void f() {} virtual void g() {}};
void foo(B* bp)
{
bp->f();
}
In the above call, there is no way of knowing which sub-type of B
bp
points to. 在上述调用中,无法知道B
bp
指向的子类型。 It could be C
, D
, or something else. 可能是C
, D
或其他。 If you step into the call you would know which sub-type of B
bp
points to. 如果您进入呼叫,您将知道B
bp
指向的子类型。
struct C : A, B {void f() {}};
struct D : B {void f() {}};
int main()
{
B* pb1 = new C;
B* pb2 = new D;
foo(pb1);
foo(pb2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.