4

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

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

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

};
4

2 回答 2

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

};
于 2012-04-19T10:11:22.753 回答
-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;
}
于 2012-04-19T10:09:25.893 回答