ano*_*non 8 c++ inheritance base-class object-address
在C struct中,我保证:
struct Foo { ... };
struct Bar {
Foo foo;
...
}
Bar bar;
assert(&bar == &(bar.foo));
Run Code Online (Sandbox Code Playgroud)
现在,在C++中,如果我有:
class Foo { ... };
class Bar: public Foo, public Other crap ... {
...
}
Bar bar;
assert(&bar == (Foo*) (&bar)); // is this guaranteed?
Run Code Online (Sandbox Code Playgroud)
如果是这样,你能给我一个参考(如"The C++ Programming Language,page xyz")吗?
谢谢!
小智 6
即使基本类的布局不能保证你想象的方式(即使成员有更多的保证),这也是有保证的:
Bar bar;
assert(&bar == (Foo*) (&bar));
Run Code Online (Sandbox Code Playgroud)
因为强制转换使用static_cast(每5.4)将&bar正确转换,并且指针到base和指向派生的指针之间的比较将类似地转换.
但是,这不能得到保证:
Bar bar;
void* p1 = &bar;
void* p2 = (Foo*)&bar;
assert(p1 == p2); // not guaranteed
Run Code Online (Sandbox Code Playgroud)