How shall I implement operator overloading in base class for base class part of derive class object?
Please see this sample code and implement base class part to implement * operator on derive class object
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;
}
};
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;
}
};
Implement a base::operator *
as below:
class base {
protected:
int x;
public:
base operator * (const base &rh) {
base b;
b.x = x * rh.x;
return b;
}
};
And call it as,
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.