c ++避免代码重复运算符重载

时间:2017-03-21 10:33:01

标签: c++ operator-overloading code-duplication

我的问题如下,让我说我有这个课程:

class ID3OBJ
{
public:
    const double X;
    const double Y;
    const double Z;
    ID3OBJ(double x, double y, double z);
    ID3OBJ();
    const ID3OBJ operator+ (const ID3OBJ param) const;
}
class Vector : public ID3OBJ
    {
    public:
        Vector(double x, double y, double z);
        Vector();
        /*const Vector const operator+ (const Vector param); */
}
class Point : public ID3OBJ
    {
    public:
        Point(double x, double y, double z);
        Point();
}
class Plane : public ID3OBJ
    {
    public:
        Point Origin;
        Vector Direction1;
        Vector Direction2;
        Vector NormalVector;
        Plane(Point Origin, Vector Normalvector);
        Plane(Point Origin, Vector Direction1, Vector Direction2);
        Plane();
}
class D3GON : public ID3OBJ, public Plane
    {
    public:
        std::vector<Point> EdgePoints;
        D3GON(Point P1, Point P2, Point P3);
    };

在我目前的代码中,我必须重新定义每个类的运算符重载,如何避免这种代码重复?

我是否必须添加转换功能?

我使用const成员值,在创建后拒绝对象更改。意味着如果必须更改任何低级别对象,则必须将其替换为新级别。请参阅下面的运算符重载:

// operator overwrites:
    const ID3OBJ ID3OBJ::operator+ (const ID3OBJ param) const { double newX, newY, newZ; newX = X + param.X; newY = Y + param.Y; newZ = Z + param.Z; return ID3OBJ(newX, newY, newZ); }

谢谢:)

1 个答案:

答案 0 :(得分:1)

Curiously recurring template pattern是要去的地方。它稍微复杂一些,因为您需要多个派生级别。但这是一个代码示例:

template <class T>
class ID3OBJ
{
public:
   double X,Y,Z;
   T operator+(const T& obj) const {
       T t;
       t.X = X + obj.X;
       t.Y=Y+obj.Y;
       t.Z=z+obj.Z;
       return t;
   }
};

class Vector : public ID3OBJ<Vector>
{
public:
    // some stuff
};

class Point : public Vector, public ID3OBJ<Point>
{
public:
    // X, Y and Z exist twice, once in Vector, once in ID3OBJ<Point>, so we must disambiguate
    using ID3OBJ<Point>::X;
    using ID3OBJ<Point>::Y;
    using ID3OBJ<Point>::Z;
};

您可以添加Vector(您将获得Vector)或仅Point,您将获得Point。更有趣的是,如果您添加PointVector,则会得到Vector结果,因为重载的运算符+解析将选择Vector::operator +