微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++:从派生类

如何解决C++:从派生类

我正在试验非(!)抽象类的构造函数/运算符和访问修饰符。使用公共继承,我理解基类成员/方法上的 protected 修饰符阻止从实例化的基/派生对象访问,但允许访问类本身和派生类。

对于 operator=() 函数,我可以利用基类方法,但是为什么这不适用于构造函数?以这种方式实现函数的唯一解决方案是将构造函数公开吗?

基类:

class Vector
{
private:
  int _x;
  int _y;
protected:
  Vector(int x,int y);
  Vector& operator=(const Vector& source);
// further constructors/operator overloads / getters & setters
};

派生类:

class Position : public Vector
{
private:
  double _rho;
  double _phi;
public:
  // further constructors/operator overloads / getters & setters

  Position& Position::operator=(const Position& source)
  {
    Vector::operator=(source); // Here the calling of a protected method of the base class is allowed,which slices the input.
    _rho = source._rho;
    _phi = source._phi;
    return *this;
  }

  Position Position::operator+(const Position& source) const
  {
    // HELP HERE: the calling of protected methods (copy-constructor/getters of the base class is NOT allowed.
    Vector vec = Vector{*this} + Vector{source};
    return Position{vec.get_x(),vec.get_y()};
  }
};

同样,这是一个实验。这个练习的目的不是让它在一般情况下工作,而是让它在不改变函数签名的情况下专门利用基类工作。

谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。