关于多态性,引用和指针是否相等? [英] Are references and pointers equal with regards to polymorphism?

查看:81
本文介绍了关于多态性,引用和指针是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是想到必须使用指针来实现多态.使用规范示例:

I always think of having to use pointers for polymorphism. Using the canonical example:

DrawEngine::render(Shape *shape)
{
    shape->draw();
    shape->visible(true);
}

并传递指向各种Shape派生类的指针.它与引用是否一样?

And passing in pointer to various Shape derived classes. Does it work the same with references?

DrawEngine::render(Shape &shape)
{
     shape.draw();
     shape.visible(true);
}

这样做是否有效:

engine.render(myTriangle); // myTriangle instance of class derived from Shape

如果这行得通,两种情况之间有什么区别吗?我试图在Stroustrup中找到信息,但是什么也没找到.

If this works, are there any differences between the two cases? I tried to find information in Stroustrup, but I found nothing.

我重新打开它是因为我想再探索一点.

I reopened this because I wanted to explore just a tad more.

因此,dynamic_cast至少是一个区别.对我来说,多态性包括对dynamic_cast的使用.

So at least one difference is dynamic_cast. For me, polymorphism includes the use of dynamic_cast.

我可以走

Rhomboid & r = dynamic_cast<Rhomboid &>(shape);

如果强制转换失败怎么办?这有什么不同吗?

What happens if the cast fails? Is this any different?

Rhomboid * r = dynamic_cast<Rhomboid*>(&shape);

推荐答案

关于多态性,引用的工作方式类似于指针.

With regard to polymorphism, references work just like pointers.

这篇关于关于多态性,引用和指针是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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