I always think of having to use pointers for polymorphism. Using the canonical example:
DrawEngine::render(Shape *shape)
{
shape->draw();
shape->visible(true);
}
And passing in po开发者_如何学Gointer to various Shape derived classes. Does it work the same with references?
DrawEngine::render(Shape &shape)
{
shape.draw();
shape.visible(true);
}
Is it even valid to do:
engine.render(myTriangle); // myTriangle instance of class derived from Shape
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.
So at least one difference is dynamic_cast. For me, polymorphism includes the use of dynamic_cast.
Can I go
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.
Regarding dynamic_cast
, a failed cast produces a nullpointer with pointers, and results in a throw of a bad_cast
(IIRC) exception with references.
One reason is that there's no such thing as a valid null-reference.
And possibly another reason (but it could just be an unintentionally useful emergent feature) is that sometimes one needs the exception and sometimes one needs the easy-to-check nullpointer, and no matter whether you have a reference or pointer at hand it takes at most a dereferencing or address operator to obtain the behavior you want.
Cheers & hth.,
Pointers help in other ways as well. Like passing a string and accepting it as char* parameter in a function.
Consider the old example of reversing a string in place:
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--;
}
}
Writing code for string manipulation like these using references won't be that simple.
精彩评论