我的问题如下,假设我有此类:

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); }


谢谢 :)

最佳答案

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。更有趣的是,如果添加PointPoint,则会得到Vector结果,因为重载的运算符+分辨率将选择Vector

关于c++ - C++避免代码重复运算符重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42924550/

10-16 16:29