这个问题帮助我理解了一些,但我的问题与他们的略有不同。
据我了解,C++ 中的基本类型转换涉及将内存中的结构重新解释为不同的结构。例如:
class Building{int sqFootage;};
class Office : public Building{int cubicles;};
int main(int argc, char** argv){
Office *foo = new Office();
/*The cubicles member appears after the sqFootage member on an Office,
* so the foo pointer is really just a Building* with some extra
* information after it.
*/
Building *bar = (Building*)foo;
return 0;
};
这里的关键点是,办公室在内存中可以被解释为建筑物,而无需对结构进行任何改变。这在多重继承的情况下会崩溃:
class Animal{bool alive;};
class WaterDweller : public Animal{float swimSpeed;};
class LandDweller : public Animal{float runSpeed;};
class Amphibian : public WaterDweller, public LandDweller{float transitionSpeed};
int main(int argc, char** argv){
Amphibian *amph = new Amphibian();
LandDweller *land = (LandDweller*)amph;
WaterDweller *sea = (WaterDweller*)amph;
}
无法解释amph
作为两个LandDweller
and a WaterDweller
无需重组Amphibian
内存中的结构。假设这些转换有任何有用的意义,它们是如何工作的?如果没有的话,会static_cast
, dynamic_cast
, or reinterpret_cast
这里合适吗?
编辑:非常感谢您的回答 Sneftel。这小博士链接您在其中一条评论中提供的内容非常有帮助,并且我会牢记避免 c 风格强制转换的建议。
对于那些好奇的人,以下是我尝试运行此代码时得到的指示:
land 0x22c8018
sea 0x22c8010
run 0x22c801c
swim 0x22c8014
land alive 0x22c8018
sea alive 0x22c8010
您可以在这里看到,即使陆地居民和水居民继承自同一基类,它们也包含自己的副本,就好像基类不同一样。这就导致了斯尼夫特尔在评论中提到的钻石问题。