类的继承例子:

以上个动态银河系的制作为例,假设我们定义了一个星星的类如下:

class Star
{
public:
Star(){}
~Star(){} void Init();
void Move(); protected:
void Draw();
void NewPos();
void Remove(); double m_x = ;
int m_y;
double m_step;
int m_color;
}; void Star::Init()
{
if (m_x == )
{
m_x = rand() % SCREEN_WIDTH;
}
else
{
m_x = ;
} m_y = rand() % SCREEN_HEIGHT;
m_step = (rand() % ) / 1000.0 + ;
m_color = (int)(m_step * / 6.0 + 0.5); // 速度越快,颜色越亮
m_color = RGB(m_color, m_color, m_color);
} void Star::Move()
{
Remove(); NewPos(); Draw();
} void Star::Draw()
{
putpixel((int)m_x, m_y, m_color);
} void Star::NewPos()
{
m_x += m_step;
if (m_x > SCREEN_WIDTH)
this->Init();
} void Star::Remove()
{
putpixel((int)m_x, m_y, );
}

接下来我们被要求制作一个矩形的星星我们该怎么做,其实矩形星星和上述的差别就在于draw()和Romove()这两个函数,所以我们可以利用类继承的方法来实现,再使用同函数名覆盖的方法来写类,有三种继承的方式如下表所示:

派生方式 基类的public成员 基类的protected成员 基类的private成员 派生方式引起的访问属性变化概括
private派生 变为private成员 变为private成员 不可见 基类中的非私有成员都成为派生类中的私有成员
protected派生 变为protected成员 变为private成员 不可见 基类中的非私有成员在派生类中的访问属性都降一级
public派生 仍为public成员 仍为protected成员 不可见 基类中的非私有成员在派生类中的访问属性保持不变

所以在这里我们采用public继承的方式,只是把其中的类方法改变即可(这里我们注意在基类中数据并不是private类型,因为若是private类不管子类是什么方式继承都是不可以调用的就算是使用同名函数进行重载):

 class RectStar : public Star
{
public:
RectStar(){}
~RectStar(){} void Move()
{
Remove();
NewPos();
Draw();
} protected:
void Draw();
void Remove();
}; void RectStar::Draw()
{
setfillcolor(m_color);
fillrectangle(m_x, m_y, m_x + , m_y + );
} void RectStar::Remove()
{
clearrectangle(m_x, m_y, m_x + , m_y + );
}

最新文章

  1. js中属性节点的应用
  2. Spring Web
  3. IQKeyboardManager在某个页面取消键盘上面的Toolbar
  4. iOS - UIApplication
  5. 【FitNess】测试框架试用
  6. [Angular 2] Share a Service Across Angular 2 Components and Modules
  7. mongod的主要参数解释
  8. angularjs 中ie兼容性的问题收集
  9. Android Assert工具类
  10. STL跨DLL使用
  11. iOS 混合网页开发 问题
  12. mysql出现Waiting for table metadata lock的原因及解决方案
  13. MC34063+MOSFET扩流 12V-5V 折腾出了高效率电路(转)
  14. 013 session_flush
  15. SSH三大框架整合步骤
  16. firefox被hao123绑架的解决办法
  17. Spring框架——AOP代理
  18. Git中的"pull request"真正比较的是什么?
  19. 微信小程序富文本中的图片大小超出屏幕
  20. linux下应用程序性能剖分神器gprofiler-tools-安装和使用

热门文章

  1. Centos7.4 yum 安装MariaDB
  2. Selenium 2自动化测试实战26(unittest单元测试框架)
  3. 内存或磁盘空间不足,word无法显示所请求的字体
  4. 利用nginx做反向代理解决前端跨域问题
  5. RN 图片处理 resizeMode
  6. CTF—攻防练习之HTTP—SQL注入(SSI注入)
  7. ‘No module named 'numpy.core._multiarray_umath’ 或者‘no module named numpy’
  8. filter_var()函数
  9. 【Python开发】urllib2异常处理
  10. flask的方法视图