代码之家  ›  专栏  ›  技术社区  ›  pm100

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

  •  41
  • pm100  · 技术社区  · 15 年前

    我总是认为必须为多态性使用指针。使用规范示例:

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

    并将指针传递给各种形状派生类。它对参考文献的作用相同吗?

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

    这样做是否有效:

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

    如果这有效,这两种情况之间有什么区别吗?我试着在史特劳斯普找到信息,但什么也没找到。

    我重新打开这个是因为我想再多探索一点。

    因此,至少有一个区别是动态铸造。对于我来说,多态性包括使用动态\u cast。

    我可以去吗

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

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

    Rhomboid * r = dynamic_cast<Rhomboid*>(&shape);
    
    3 回复  |  直到 10 年前
        1
  •  46
  •   Alex Emelianov    15 年前

        2
  •  10
  •   Cheers and hth. - Alf    15 年前

    dynamic_cast bad_cast

        3
  •  0
  •   vinayvasyani    15 年前

    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--;
    }
    }