【发布时间】:2021-06-16 09:47:31
【问题描述】:
有没有办法重用基类的operator+(...) 方法,类似于下面示例中使用赋值运算符operator=(...) 的方式?
重要提示:我不想使用抽象类/虚拟方法,我只是对下面的示例感到好奇,以便我完全理解继承的“基本”用法,而无需过多介绍多态性!在下面的例子中,operator=()这样使用就可以成功,用operator+()可以吗?
基类:
class Vector
{
private:
int _x;
int _y;
protected:
// constructors & destructors here
Vector& operator=(const Vector& source){...}
Vector operator+(const Vector& source) const{...}
};
派生类:
class Position : public Vector
{
private:
double _rho;
double _phi;
public:
// constructors & destructor here
Position& operator=(const Position& source)
{
Vector::operator=(source); // slices source to its base-class part
_rho = source._rho;
_phi = source._phi;
return *this;
}
Position operator+(const Position& source) const
{
/*
* HELP NEEDED HERE:
* Some way of calling Vector::operator+() to avoid
* code repetition and ensure consistency with the
* operator+ definition in the base class
*/
}
};
谢谢
【问题讨论】:
标签: c++ inheritance operator-overloading