关于多态性,引用和指针是否相等?

我一直认为必须使用多态指针。 使用规范的例子:

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

并传递指向各种Shape派生类的指针。 它是否与参考一样工作?

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

是否有效:

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

如果这样做,这两个案件有什么分别吗? 我试图在Stroustrup中find信息,但是我什么也没find。

我重新开放了这个,因为我想多探索一下。

所以至less有一个区别是dynamic_cast。 对我来说,多态包括使用dynamic_cast。

我可以去吗

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

如果演员失败会发生什么? 这有什么不同吗?

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

关于多态性,引用就像指针一样工作。

关于dynamic_cast ,一个失败的强制转换产生一个带有指针的空指针,并导致一个带引用的bad_cast (IIRC)exception。

一个原因是没有这样的事情作为一个有效的空引用。

可能的另一个原因(但它可能只是一个无意识的有用的紧急function)是有时候需要这个exception,有时需要一个易于检查的空指针,不pipe你是否有一个引用或指针,大多数是取消引用或地址运算符来获取所需的行为。

干杯&hth。,

指针也以其他方式提供帮助。 像传递一个string,并接受它作为函数中的char *参数。

考虑反转string的旧例子:

 void reversestring(char* myString) { int firstPos=0; int lastPos=myString.length - 1; while (firstPos < lastPos) { char temp=myString[firstPos]; myString[firstPos]=myString[lastPos]; myString[lastPos]=temp; firstPos++; lastPos--; } } 

使用引用编写string操作的代码不会那么简单。