如何在基类中为派生类对象的基类部分实现运算符重载?

时间:2012-04-19 09:59:39

标签: c++

如何在基类中为派生类对象的基类部分实现运算符重载?

请参阅此示例代码并实现基类部分以在derive类对象上实现*运算符

class base {
     int x;
public:

};

class der : public base {
    int y;
public:
    const der operator*(const der& rh) {
        der d;
        d.y = y * rh.y;
        return d;
    }

};

2 个答案:

答案 0 :(得分:1)

class base {
     int x;
public:
     base & operator *=(const base &rh) {
         x*=rh.x;
         return *this;
     }
     base operator *(const base &rh) {
         base b = *this;
         b*=rh;
         return b;
     }
};

class der : public base {
    int y;
public:
    using base::operator*;
    der & operator*= (const der& rh) {
         base::operator*=(rh);
         y*=rh.y;
         return *this;
    }
    const der operator*(const der& rh) {
        der d = *this;
        d*=rh;
        return d;
    }

};

答案 1 :(得分:-1)

实施base::operator *,如下所示:

class base {
protected:
  int x;
public:
  base operator * (const base &rh) {
    base b;
    b.x = x * rh.x;
    return b;
  }
};

并称之为,

der operator * (const der& rh) {
  der d;
  Base &b = d;  // <---- assign a temporary reference of 'base'
  b = static_cast<Base&>(*this) * rh; // <---- invoke Base::operator *
  d.y = y * rh.y;
  return d;
}