实验4 继承
实验三
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 class Car { 5 public: 6 Car(string z,string x,int y,int m=0):maker(z),model(x),year(y),odometers(m) {}; 7 void info(){ 8 cout<<"制造商:\t"<<maker<<endl; 9 cout<<"型号:\t\t"<<model<<endl; 10 cout<<"生产年份:\t"<<year<<endl; 11 cout<<"当前行车里程数:"<<odometers<<endl; 12 } 13 void update_odometers(int m){ 14 if(m<odometers) 15 cout<<"waring please enter again"<<endl; 16 odometers=m; 17 } 18 private: 19 string maker; 20 string model; 21 int year; 22 int odometers; 23 };
#include <iostream> #include "electricCar.hpp" int main() { using namespace std; // test class of Car Car oldcar("Audi", "a4", 2016); cout << "--------oldcar's info--------" << endl; oldcar.update_odometers(25000); oldcar.info(); cout << endl; // test class of ElectricCar ElectricCar newcar("Tesla", "model s", 2016); newcar.update_odometers(2500); cout << "\n--------newcar's info--------\n"; newcar.info(); }
1 #include<iostream> 2 3 class Battery { 4 public: 5 Battery(string a="70-kmh"):capacity(a) {}; 6 string get_capacity(){ 7 return capacity; 8 }; 9 private: 10 string capacity; 11 };
electriccar.hpp
实验四
1 #ifndef PETS_HPP 2 #define PETS_HPP 3 #include <iostream> 4 #include<string> 5 using namespace std; 6 class MachinePets{ 7 public: 8 MachinePets(const string s):nickname(s){}; 9 string get_nickname()const{ 10 return nickname; 11 } 12 virtual string talk(){ 13 } 14 private: 15 string nickname; 16 }; 17 18 class PetCats:public MachinePets{ 19 public: 20 PetCats(const string s):MachinePets(s){ 21 22 }; 23 string talk(){ 24 return "miao wu ~"; 25 } 26 }; 27 28 class PetDogs:public MachinePets{ 29 public: 30 PetDogs(const string s):MachinePets(s){}; 31 string talk(){ 32 return "wang wang wang !"; 33 } 34 }; 35 #endif
1 #include <iostream> 2 #include "pets.hpp" 3 #include<string> 4 void play(MachinePets *ptr) 5 { 6 std::cout << ptr->get_nickname() << " says " << ptr->talk() << std::endl; 7 } 8 9 int main() 10 { 11 PetCats cat("miku"); 12 PetDogs dog("da huang"); 13 14 play(&cat); 15 play(&dog); 16 }
小结
1、在实验三中既用到了类的继承又用到了类的组合,组合中类对象的private成员也是不能在类中直接访问的,所以需要调用公有接口
2、virtual函数可以让派生类在和基类有同名函数时,基类的指针能指向传入的派生类中的函数