两个不同类的泛型函数
Generic function for two different classes
我正在尝试创建一个泛型函数,该函数接收同一类的两个对象并返回相同的对象
这是我的两个类: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 点差异(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;
}
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 链表的泛型函数remove()与成员函数remove)
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何编写将要继承的泛型代码?
- C++17 如何保存泛型可调用对象以供以后使用
- 使用宏扩展的泛型:为什么指令缓存使用不当?
- C++泛型类错误,问题出在哪里?
- C++泛型类,单独实现?
- 将参数传递给泛型 lambda 时复制构造函数不正确
- 泛型枚举和其他类型的重载模板函数
- 使用泛型类型推送到堆栈时出现问题
- 可变参数泛型 lambda 和函数重载
- C++ 泛型和多态性:这种模式可行吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- Java 是否像C++模板一样具有泛型推论?
- 为堆栈实现泛型集合
- 泛型方法指针.reinterpret_cast指向不同类的方法指针,这是 UB 吗?
- 两个不同类的泛型函数