我正在阅读 this不幸的是,无法深入理解为什么编译器不允许从 Derived** 转换为 Base**。我也看过this它只提供了 parashift.com 链接的更多信息。
编辑:
让我们逐行分析这段代码:
Car car;
Car* carPtr = &car;
Car** carPtrPtr = &carPtr;
//MyComment: Until now there is no problem!
Vehicle** vehiclePtrPtr = carPtrPtr; // This is an error in C++
//MyComment: Here compiler gives me an error! And I try to understand why.
//MyComment: Let us consider that it was allowed. So what?? Let's go ahead!
NuclearSubmarine sub;
NuclearSubmarine* subPtr = ⊂
//MyComment: this two line are OK too!
*vehiclePtrPtr = subPtr;
//MyComment: the important part comes here... *vehiclePtrPtr is a pointer to
//MyComment: a vehicle, particularly in our case it points to a Car object.
//MyComment: Now when I assign to the pointer to the Car object *vehiclePtrPtr,
//MyComment: a pointer to NuclearSubmarine, then it should just point to the
//MyComment: NuclearSubmarine object as it is indeed a pointer to a Vehicle,
//MyComment: isn't it? Where is my fault? Where I am wrong?
// This last line would have caused carPtr to point to sub!
carPtr->openGasCap(); // This might call fireNuclearMissle()!
最佳答案
一碗香蕉不是一碗水果的原因基本相同。如果一碗香蕉是一碗水果,你可以把一个苹果放进碗里,它就不再是一碗香蕉了。
只要您只检查碗,转换是无害的。但是一旦你开始修改它,转换就变得不安全了。这是要牢记的关键点。 (这就是为什么不可变 Scala 集合实际上允许转换,但可变集合禁止转换的确切原因。)
与您的示例相同。如果有从 Derived**
到 Base**
的转换,您可以放置一个指向苹果的指针,而类型系统 promise 只存在指向香蕉的指针。轰隆隆!
关于c++ - 从派生**转换为基础**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8026040/