两个不同类的泛型函数

Generic function for two different classes

本文关键字:同类 泛型 函数 两个      更新时间:2023-10-16

我正在尝试创建一个泛型函数,该函数接收同一类的两个对象并返回相同的对象

这是我的两个类:Point2DPoint3D

class Point2D
{
 public:
           Point2D();
           Point2D(int,int);
           int getX() const;
           int getY() const;
           void setX(int);
           void setY(int);
 protected:
             int x;
             int y;
};

class Point3D:public Point2D
{
  public:   Point3D();
            Point3D(int,int,int);
            void setZ(int);
            int getZ() const;
  protected:
             int z;
};
对于 Point2D

:我正在尝试返回一个 Point2D 对象,其 X,Y 坐标是 2 个 Point2D 对象之间的差异

对于 Point3D

:我正在尝试返回一个 Point3D 对象,其 X,Y,Z 坐标是 2 个 Point3D 对象之间的差异

我可以创建一个通用函数来处理这两个??? .

以下是我到目前为止所拥有的,但它只处理 Point2D 对象,如何将 Point3D 对象集成到下面的通用函数中

模板 T 点差异(T pt1, T pt2)

{ T pt3;

pt3.x = pt1.x - pt2.x;

pt3.y = pt1.y - pt2.y;

返回 pt3;
}

我在想这样的事情,但问题是 Point2D 对象没有 Z 坐标

模板 T 点差异(T pt1, T pt2)
{ T pt3;

pt3.x = pt1.x - pt2.x;

pt3.y = pt1.y - pt2.y;

pt3.z = pt1.z - pt2.z

返回 pt3; }

有人可以帮我吗,谢谢

我认为您可以为每个类设置一个 Diff 函数。

对于类 Point2D,它:

Point2d Diff(Point2D &d) {
    Point2d pt;
    pt.x = this->x - d.x;
    pt.y = this->y - d.y;
    return pt;
} 

对于类 Point3D:

Point3d Diff(Point3D &d) {
    Point3d pt;
    pt.x = this->x - d.x;
    pt.y = this->y - d.y;
    pt.z = this->z - d.z;
    return pt;
} 

然后,你的函数是这样写的:

template T PointDiff(T pt1, T pt2) {
        return pt1.Diff(pt2);
}

我希望这对你有帮助。

您可以覆盖每个类的减号运算符:

Point2D operator-(Point2D &pt1, Point2D &pt2)
{
    Point2D ret;
    ret.x = pt1.x - pt2.x;
    ret.y = pt2.y - pt2.y;
    return ret;
}
Point3D operator-(Point3D &pt1, Point3D &pt2)
{
    Point3D ret;
    ret.x = pt1.x - pt2.x;
    ret.y = pt2.y - pt2.y;
    ret.z = pt1.z - pt2.z;
    return ret;
}

您还需要将operator-声明为两个类的好友:

class Point2D
{
public:
    Point2D();
    Point2D(int,int);
    int getX() const;
    int getY() const;
    void setX(int);
    void setY(int);
    friend Point2D operator-(Point2D &pt1, Point2D &pt2);
protected:
    int x;
    int y;
};
class Point3D:public Point2D
{
public:
    Point3D();
    Point3D(int,int,int);
    void setZ(int);
    int getZ() const;
    friend Point3D operator-(Point3D &pt1, Point3D &pt2);
protected:
    int z;
};

然后,您只需使用减法即可在程序中使用它

int main(int argc, char **argv)
{
    Point2D a, b, c;
    a.setX(4);
    a.setY(5);
    b.setX(2);
    b.setY(-10);
    c = a - b;
    std::cout << c.getX() << " " << c.getY() << std::endl;
}