Are references and pointers equal with regards to polymorphism?

前端 未结 3 713
南笙
南笙 2020-12-08 10:05

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

DrawEngine::render(Shape *shape)
{
    shape->draw();
    shape-&g         


        
3条回答
  •  萌比男神i
    2020-12-08 10:28

    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.

提交回复
热议问题