加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C是否可以不继承成员?

发布时间:2020-12-16 10:13:39 所属栏目:百科 来源:网络整理
导读:我很确定不是,但无论如何我都会问… 这是一个例子: 假设我有一个名为Elipse的类: class Elipse{private: double d_m_lAxis; // the length of the large Axis of the elipse double d_m_sAxis; // short axis//Point is a struct of 2 doubles (x and y) P
我很确定不是,但无论如何我都会问…
这是一个例子:
假设我有一个名为Elipse的类:

class Elipse
{
private:
  double d_m_lAxis; // the length of the large Axis of the elipse
  double d_m_sAxis; // short axis
//Point is a struct of 2 doubles (x and y)
  Point P_m_focal1; //focal point 1
  Point P_m_focal2; //focal point 2
protected:
  Point P_m_center; 

public:
  Elipse(Point _P_lowerLeft,Point _L_upperRight)
  {
    //draw elipse in a rectangle,just like in paint
  }
}

现在我想从Elipse继承Circle(因为Circle是一个Elipse,两个轴的长度相同):

class Circle : public Elipse   
{
private:
  double d_m_radius;
public:
  Circle(Point _P_lowerLeft,double _d_diameter) :
    Elipse(_P_lowerLeft,/*get the upper ight*/
      Point(_P_lowerLeft.x + _d_diameter,_P_lowerLeft.y + _d_diameter))
      {
        // draw a circle in a square,just like in paint
      }
}

所以现在我得到了我想要的类,并且它无法访问Elipse的任何私有成员,这些成员将在Circle中变得多余.
但是,据我所知,这些成员仍然是继承的,而子类根本无法访问它们.这使得类的大小不必要地大,并且还可以通过从Elipse继承的函数来访问这些成员,除非它们被覆盖.

有没有办法不继承成员?

解决方法

数学术语“圆是一个椭圆,其中[…]”应该被改写为更多类型的“对于每个圆,存在一个椭圆,其中[…]描述了同一组点”.

考虑到这一点,您的实现应允许从Circle对象创建Ellipse对象,但不允许多态替换.
一种可能性是显式转换运算符:

class Elipse
{
  // as you defined
};

class Circle
{
  // As you defined
  explicit operator Ellipse()
  {
    Point lower_left,upper_right;
    // calculate the two points
    return Ellipse(lower_left,upper_right);
  }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读