我正在尝试创建一个泛型函数,它接受同一个类的两个对象并返回相同的对象
这是我的两个班级:Point2D
和Point3D
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 PointDiff(T pt1,T pt2)
{
T pt3;pt3.x = pt1.x - pt2.x;
pt3.y = pt1.y - pt2.y;
返回pt3;
}
我在想这样的事情,但问题是 Point2D对象没有Z坐标
模板T PointDiff(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; }
有人可以帮助我,谢谢
答案 0 :(得分:3)
我认为你可以为每个类设置一个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);
}
我希望这会对你有所帮助。
答案 1 :(得分:0)
您可以覆盖每个类的减号运算符:
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;
}