Saturday, October 18, 2008

UsingClass3-inheritance

//animal.h
#include < iostream.h>
class Animal_T{
public:
  Animal_T():age(1){
    name=new char();
  }
  bool ChangeTheName(){
    cin>>name;
    return true;
  }
  char* DisplayName(){
    return name;
  }
  int DisplayAge(){
    return age;
  }
  bool PassDay(){
    cout<<"a day pass..."<< endl;
    age++;
    return true;
  }
  virtual bool ChangeName()=0;
  virtual bool Display()=0;
  virtual bool Cry()=0;
private:
  char *name;
  int age;
};
class Dog_T:public Animal_T{
public:
  Dog_T(){
    ChangeName();
  }
  bool ChangeName(){
    cout<<"input your dog's new name:";
    Animal_T::ChangeTheName();
    return true;
  }
  bool Display(){
    cout<<"your dog's name is "<< DisplayName()<< endl;
    cout<<"your dog is "<< DisplayAge()<<" days old"<< endl;
    return true;
  }
  bool Cry(){
    cout<<"WoWo"<< endl;
    return true;
  }
};
class Cat_T:public Animal_T{
public:
  Cat_T(){
    ChangeName();
  }
  bool ChangeName(){
    cout<<"input your cat's new name:";
    Animal_T::ChangeTheName();
    return true;
  }
  bool Display(){
    cout<<"your cat's name is "<< DisplayName()<< endl;
    cout<<"your cat is "<< DisplayAge()<<" days old"<< endl;
    return true;
  }
  bool Cry(){
    cout<<"MiaoMiao"<< endl;
    return true;
  }
};
//main.cpp
#include "animal.h"
int main(){
  int n;
  Animal_T *pet;
  int kind=0;
  ///////////////////
  //菜单
  ///////////////////
  do{
    while(!(kind==1 || kind==2)){
      cout<<"1.cat 2.dog"<< endl;
      cout<<"your input is:";
      cin>>kind;
      cout<< endl;
      if(kind==1){
        pet=new Cat_T();
      }else if(kind==2){
        pet=new Dog_T();
      }
    };
    do{
      cout<< endl;
      cout<<"Menu:"<< endl;
      cout<<" 1.Display info"<< endl;
      cout<<" 2.Past one day"<< endl;
      cout<<" 3.Cry"<< endl;
      cout<<" 4.Charge name"<< endl;
      cout<<" 5.Charge pet"<< endl;
      cout<<" 6.Exit"<< endl;
      cout<<"and your input is:";
      cin>>n;
      cout<< endl;
    }while(n<1 || n>6);
    switch(n){
    case 1:
      pet->Display();
      break;
    case 2:
      pet->PassDay();
      break;
    case 3:
      pet->Cry();
      break;
    case 4:
      pet->ChangeName();
      break;
    case 5:
      delete pet;
      kind=0;
      break;
    }
  }while(n!=6);
  ///////////////////////
  ///////////////////////
  cout<<"See you"<< endl;
  return 0;
}

--------------------------------------------------------------------------------

this is a example of class inheritance with virtual functions. so, i don't want to talk to much for this.

but, if you have any question of this, please ask. i will try my best answer you.

No comments:

Post a Comment