【问题标题】:c++ avoid code duplication operator overloadingc++避免代码重复运算符重载
【发布时间】:2017-03-21 10:33:01
【问题描述】:

我的问题如下,假设我有这些课程:

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

谢谢你:)

【问题讨论】:

  • 如果所有countableObjectsInterface 都以相同的方式添加,则只需提供该方式,而不提供Animals operator+(Animals obj)。如果 AnimalsSloths 添加不同,您将不得不提供不同的实现,无法绕过它。也许添加 2 个 Sloths 来创建更多 Sloths 根本不是正确的做法。
  • @n.m.:嗯,他们必须吃东西,虽然我听说他们更喜欢生菜。
  • 这是一个例子,我正在使用 3D 对象。如果我不为我的子类提供任何重载,则运算符会返回基类。我将添加运算符定义。
  • 请发布一个真实的例子。答案很大程度上取决于您尝试做什么的确切细节。
  • @n.m.见上文

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


【解决方案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 +

【讨论】:

  • 谢谢,这就是我一直在寻找的 :)
猜你喜欢
  • 2014-03-07
  • 2011-10-27
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多