【问题标题】:Function with two objects as arguments以两个对象为参数的函数
【发布时间】:2012-07-23 04:58:47
【问题描述】:

我有一个基类Shape 和一些其他派生类,如CircleRectangle 等等。我想将两个对象传递给函数getDistance(object1, object2) 来计算两个对象之间的距离。

我的问题是,这个函数应该如何声明和实现?你认为我应该使用template,因为我可能会传递来自两个不同类的两个对象吗?如果是这样,template 会是什么样子?

感谢任何帮助

【问题讨论】:

    标签: c++ templates pass-by-reference


    【解决方案1】:

    通常你会在你的基类上使用一个纯虚拟。您已经从 Shape 继承,所以模板对于这个问题来说是多余的。

    虚拟 GetPosition() 添加到基本 Shape 类,并使 getDistance() 采用两个 Shape 指针(或引用)。例如:

    class Shape
    {
    public:
        ~virtual Shape() {}  // Make sure you have a virtual destructor on base
    
        // Assuming you have a Position struct/class
        virtual Position GetPosition() const = 0;
    };
    
    class Circle : public Shape
    {
    public:
        virtual Position GetPosition() const;  // Implemented elsewhere
    };
    
    class Rectangle : public Shape
    {
    public:
        virtual Position GetPosition() const;  // Implemented elsewhere
    };
    
    float getDistance(const Shape& one, const Shape& Two)
    {
        // Calculate distance here by calling one.GetPosition() etc
    }
    
    // And to use it...
    Circle circle;
    Rectangle rectangle;
    getDistance(circle, rectangle);
    

    编辑:Pawel Zubrycki 是正确的 - 在基类上添加了虚拟析构函数以实现良好的测量。 ;)

    【讨论】:

    • 哇,这真是个好主意。我的课程与您发布的内容略有不同,但您的观点让我找到了解决方案。非常感谢斯科蒂 :)
    • @JackintheBox:不客气。请在我的回答上单击接受好吗? :)
    • Shape类中应该有虚析构函数。
    【解决方案2】:

    你可以用模板来做:

    template<class S, class T> getDistance(const S& object1, const T& object2) {
    

    只要两个对象具有相同的函数或变量(即 x 和 y)即可计算距离。

    否则你可以使用继承:

    getDistance(const Shape& object1, const Shape& object2)
    

    只要 Shape 类强制使用类似 getPosition 的函数:

    getPosition() = 0; (in Shape)
    

    我建议继承,因为它会更清晰,更容易理解和控制错误,但会牺牲一点速度。

    【讨论】:

      【解决方案3】:

      另一种选择是使用参数多态性:

      struct Position {
          float x, y;
      };
      
      class Circle {
      public:
          Position GetPosition() const;  // Implemented elsewhere
      };
      
      class Rectangle {
      public:
          Position GetPosition() const;  // Implemented elsewhere
      };
      
      float getDistance(const Position &oneP, const Position twoP); // Implemented elsewhere
      
      template<class K, class U>
      float getDistance(const K& one, const U& two) {
          return getDistance(one.GetPosition(), two.GetPosition());
      }
      

      【讨论】:

        猜你喜欢
        • 2013-03-20
        • 2017-03-01
        • 2018-08-11
        • 2020-01-07
        • 1970-01-01
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多