rah*_*man 15 c++ pointers reference
"我确信有几十个问题都有相同的标题.其中很多都是重复的.我的也可能是重复的,但我找不到任何问题.所以我试着让它变得非常简洁,简洁."
我有这样的层次结构:
class Shape {
public:
virtual void virtualfunc() { std::cout << "In shape\n"; }
};
class Circle: public Shape {
public:
void virtualfunc() { std::cout << "In Circle\n"; };
};
Run Code Online (Sandbox Code Playgroud)
当我在指针的帮助下使用类时,函数按照我的预期调用:
int main() {
Shape shape_instance;
Shape* ref_shape = &shape_instance ;
Circle circle_instance;
Circle* ref_circle = &circle_instance;
ref_shape = dynamic_cast<Shape*> (ref_circle);
ref_shape->virtualfunc();
}
Run Code Online (Sandbox Code Playgroud)
这里程序调用virtualfunc()派生类,结果自然是:In Circle
现在,我想摆脱指针,改为使用引用,并获得相同的结果.所以我做了一些微不足道的修改main(),看起来像这样:
int main() {
Shape shape_instance;
Shape& ref_shape = shape_instance;
Circle circle_instance;
Circle& ref_circle = circle_instance;
ref_shape = dynamic_cast<Shape&>(ref_circle);
ref_shape.virtualfunc();
}
Run Code Online (Sandbox Code Playgroud)
但这一次,程序调用virtualfunc()基类,结果是:In Shape
如果您让我知道我缺少哪些参考概念以及如何更改main()中的引用以获得指针版本中的结果,我将不胜感激.
谢谢
Dav*_*eas 18
参考不能重新安排.在初始化中初始化引用后,它将成为引用对象的别名,并且无法与其区分.后者的任务:
ref_shape = dynamic_cast<Shape&>(ref_circle);
Run Code Online (Sandbox Code Playgroud)
真正意思:
shape_instance = dynamic_cast<Shape&>(ref_circle);
Run Code Online (Sandbox Code Playgroud)
另一方面,您可以绑定对该对象的新引用(并且您不需要dynamic_cast,因为从引用转换为对base的引用的转换是隐式的):
Shape & another_ref = ref_circle;
another_ref.virtualfunc(); // Dispatches to Circle::virtualfunc
Run Code Online (Sandbox Code Playgroud)
这就是你Circle的目标Shape.
ref_shape = dynamic_cast<Shape&>(ref_circle);
// ^ here
ref_shape.virtualfunc();
Run Code Online (Sandbox Code Playgroud)
ref_shape已被定义为参考shape_instance.
您没有复制引用本身,因为无法重新分配引用.您正在将实际对象复制到Shape对象.它存储在shape_instance.
您可以通过尝试此代码来验证这一点.它会打印出来In Circle.
dynamic_cast<Shape&>(ref_circle).virtualfunc();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |