对于派生类对象的基类部分,如何在基类中实现运算符重载?
请查看此示例代码并实现基类部分以在派生类对象上实现 * 运算符
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;
}
};
关于c++ - 对于派生类对象的基类部分,如何在基类中实现运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10225716/