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中变得多余. 有没有办法不继承成员? 解决方法
数学术语“圆是一个椭圆,其中[…]”应该被改写为更多类型的“对于每个圆,存在一个椭圆,其中[…]描述了同一组点”.
考虑到这一点,您的实现应允许从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); } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |