其他分享
首页 > 其他分享> > 实验四 继承

实验四 继承

作者:互联网

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Car{
 5 public:
 6     Car(string maker0,string model0,int year0,int odometers0=0):maker(maker0),model(model0),year(year0),odometers(odometers0){};
 7     void info()const;
 8     void update_odometers(int new_odometers);
 9 private:
10     string maker,model;
11     int year,odometers;
12 };
13 void Car::info()const
14 {
15     cout<<"maker:"<<maker<<endl;
16     cout<<"model:"<<model<<endl;
17     cout<<"year:"<<year<<endl;
18     cout<<"odometers:"<<odometers<<endl;
19 }
20 void Car::update_odometers(int new_odometers)
21 {
22     if(new_odometers<odometers)
23         cout<<"数据错误,请重新输入"<<endl;
24     odometers=new_odometers; 
25 }
26 class Battery{
27 public:
28     Battery (int capacity0=70):capacity(capacity0){};
29     int get_capacity(){return capacity;}
30 private:
31     int capacity;
32 };
33 class ElectricalCar:public Car
34 {
35 public:
36     ElectricalCar(string maker0,string model0,int year0,int odometers0=0,int capacity0=70):Car(maker0,model0,year0,odometers0),battery(capacity0){};
37     void info();
38     private :
39         Battery battery;
40 };
41  void ElectricalCar:: info()
42  {
43       Car::info();
44        cout << "capacity:" << battery.get_capacity() << endl;
45  }
46 int main(){
47     using namespace std;
48     Car oldercar("Audi","a4",2016);
49     cout<<"------oldercar is info------"<<endl;
50     oldercar.info();
51     cout<<endl;
52     ElectricalCar newcar("Tesla","model s",2016);
53     newcar.update_odometers(2500);
54     cout<<"\n-------newcar's info-------\n";
55     newcar.info();
56 }
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class MachinePets
 5 {
 6 public:
 7     MachinePets( string s):nickname(s){}
 8     virtual string talk(){return "a~";}
 9     string get_nickname()const{return nickname;}
10 private:
11     string nickname;
12  };
13  class PetCats:public MachinePets
14  {
15 public:
16     PetCats(const string s):MachinePets(s){}
17     string talk(){return "miao wu";}
18  };
19  class PetsDogs:public MachinePets
20  {
21 public:
22     PetDogs(const string s):MachinePets(s){}
23     string talk(){return "wa wa";}
24  }; 
25  void play(MachinePets *ptr){
26      cout<<ptr->get_nickname<<"says"<<ptr->talk<<endl;
27      
28  }
29  int main(){
30      PetsCats cat("mw");
31      PetsDogs dog("dahuang");
32      play(&cat);
33      play(&dog);
34  }

 

标签:const,string,继承,int,实验,MachinePets,include,public
来源: https://www.cnblogs.com/617178sjq/p/15625656.html