c++训练营---继承,多态,重载

来源:互联网 发布:中泰铁路 知乎 编辑:程序博客网 时间:2024/05/19 10:52

// demo.cpp : 定义控制台应用程序的入口点。
//通过此例程了解c++的类,继承,多态,重载,设计模式里的简单工厂方法



#include "stdafx.h"#include <iostream>#include <string>using namespace std;//鸟的抽象类,为用户提供接口class CBird{public: //c++中的类默认是内联的,如果在类声明的同时进行初始化就享有内联特性,同时在初始化列表里进行初始化比在构造函数体内进行初始化性能要好,初始化的顺序要和成员变量声明时的顺序相同 //重载构造函数 CBird(float weight,float flyspeed,string name):m_weight(weight),m_flySpeed(flyspeed),m_name(name) { } //析构函数定义为虚的,因为我们的CBird类是可以被继承的类,当我们向上类型转化时,要将子类的对象赋给父类指针,这样,当析构时可以确定析构对象 virtual ~CBird() { } //纯虚函数 virtual void fly() const=0; //纯虚函数 virtual float GetWeight() const=0; virtual void ShowCount()const=0; virtual void Show() const=0;//保护类型在本类内核私有类型没有区别,但是可以被子类继承protected: float m_weight; float m_flySpeed; string m_name; //保存鸟的数目,静态数据成员隶属于类本身,而不属于哪个特定对象 static  int m_Count; //一个类内的枚举类型,用来设置鸟的总数是否越过这个边界:10 enum {  m_Bound=10 };};int CBird::m_Count=0;//注意:因为CBird类是抽象类,所以不能有实现部分     //黄鹂鸟,公有继承与CBird类class CYellowbird:public CBird{public: CYellowbird(float weight,float flyspeed,string name):CBird(weight,flyspeed,name) {  if (m_Count<=m_Bound)  {   m_Count++;  } } ~CYellowbird() {  m_Count--;  cout<<"Yellowbird Destroyed"<<endl; } void fly()const {  cout<<"Yellowbird fly"<<endl; } float GetWeight()const {  return m_weight; } void Show()const {   cout<<"我是"<<m_name<<"我能唱歌"<<endl; } void ShowCount()const {  cout<<"当前鸟的个数:"<<m_Count<<endl; }};     class CPeacock:public CBird{public: CPeacock(float weight,float flyspeed,string name):CBird(weight,flyspeed,name) {  if (m_Count<=m_Bound)  {   m_Count++;  } } ~CPeacock() {  m_Count--; } void fly()const {  cout<<"Peacock fly"<<endl; } float GetWeight()const {  return m_weight; } void Show()const {  cout<<"我是"<<m_name<<"我能开屏!"<<endl; } void ShowCount()const {  cout<<"当前鸟的个数:"<<m_Count<<endl; }};class CBirdSimpleFactory  {  public:   CBirdSimpleFactory(void);  public:   ~CBirdSimpleFactory(void);  public:   /* 静态工厂方法 */   static CBird * CreateBird(const string & name,const float &weight,const float &speed);};  CBird * CBirdSimpleFactory::CreateBird(const string & name,const float &weight,const float &speed){ if (name=="黄鹂") {  return new CYellowbird(weight,speed,name); } if (name=="孔雀") {  return new CPeacock(weight,speed,name); } return NULL;}    int _tmain(int argc, _TCHAR* argv[]){ CBird *pBird=NULL; pBird=CBirdSimpleFactory::CreateBird("黄鹂",120,120); pBird->fly(); pBird->Show(); cout<<"我的重量是:"<<pBird->GetWeight()<<endl; pBird->ShowCount(); cout<<endl; pBird=CBirdSimpleFactory::CreateBird("孔雀",100,120); pBird->fly(); pBird->Show(); cout<<"我的重量是:"<<pBird->GetWeight()<<endl; pBird->ShowCount(); return 0;} 


 

原创粉丝点击