问题 A
如果我有两个类:“父亲”和“MyClassa”,我想这样做:
father* a;
MyClassa b;
a = &b;
((MyClassa *)a) - > b();
我可以像上面的示例一样进行转换(b()
是属于 MyClassa
类的函数,在 father
中找不到类)。
但是当我这样做的时候:
father* a;
MyClassa b;
a = &b;
a = ((MyClassa *)a);
a->b();
它对我不起作用,并告诉我他的 b()
函数在该类中不存在(就像转换不起作用一样)。
这两个代码示例实际上有什么区别,是什么导致了这种差异?
问题 B
当我使用“dynamic_cast”将父亲塑造成这样的 child 时:
Father * fp= new Father;
Child * cp = dynamic_cast<Child *> fp;
它返回指针的“0”值。 但是当我对引用做同样的事情时:
Father & fp= new Father;
Child & cp = dynamic_cast<Child &> fp;
它引发错误“错误转换”。
为什么会有差异?
最佳答案
在这一行
a = ((MyClassa *)a);
该术语被强制转换为 MyClassa*
,但随后返回到 father*
(在作业中),因此您最终得到了一个 father*
.
关于你的第二个问题:从父亲到 child 的引用是不可能的,而且在多态性方面也是“错误的”
关于c++ - 关于cpp中casting objects的两个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40636551/