从派生**到基本**的转换 [英] Conversion from Derived** to Base**

查看:160
本文介绍了从派生**到基本**的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读,很遗憾,深入了解为什么编译器不允许从Derived **转换为Base **。此外,我还看过,其中没有更多信息比parashift.com的链接。

I was reading this and unfortunately could not understand in depth why the compiler does not allow conversion from Derived** to Base**. Also I have seen this which gives no more info than the parashift.com's link.

编辑:

让我们逐行分析这段代码:

Let us analyze this code line by line:

   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()!


推荐答案

基本上这就是为什么一碗香蕉不是一碗水果。如果一碗香蕉是一碗水果,你可以把一个苹果放在碗里,它不再是一碗香蕉。

It's basically the same reason why a bowl of bananas is not a bowl of fruits. If a bowl of bananas were a bowl of fruits, you could put an apple into the bowl, and it would no longer be a bowl of bananas.

只要您检查碗,转换是无害的。但是,一旦您开始修改,转换就会变得不安全。这是要记住的关键点。 (这是不可变的Scala集合实际允许转换的确切原因,但可变集合禁止它。)

As long as you only inspect the bowl, the conversion is harmless. But as soon as you start modifying it, the conversion becomes unsafe. This is the key point to bear in mind. (This is the precise reason why the immutable Scala collections actually allow the conversion, but the mutable collections prohibit it.)

与您的示例相同。如果有从 Derived ** Base ** 的转换,您可以将指针指向一个苹果类型系统承诺只有一个指向香蕉的指针可以存在。 om!

Same with your example. If there was a conversion from Derived** to Base**, you could put a pointer to an apple were the type system promised only a pointer to a banana could exist. Boom!

这篇关于从派生**到基本**的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆