实验四
ELectricCar.hpp:
#ifndef ELECTRICCAR_H #define ELECTRICCAR_H #include<iostream> #include<string> using namespace std; class Battery { public: Battery(int x0 = 70) :capacity{ x0 } {} int get_capacity() { return capacity; } private: int capacity; }; class Car { public: Car(string s1,string s2,int x1):maker(s1),model(s2),year(x1),odometers(0){} void info(); void update_odometers(int u); string get_maker() { return maker; } string get_model() { return model; } int get_year() { return year; } int get_odometers() { return odometers; } private: string maker, model; int year, odometers; }; void Car::info() { cout << "maker:\t" << maker << endl; cout << "model:\t" << model << endl; cout << "year:\t" << year << endl; cout << "odometers:\t" << odometers << endl; } void Car::update_odometers(int u) { if (u + odometers >= odometers) { odometers += u; } else cout << "warning! incorrect update" << endl; } class ElectricCar :public Car { public: ElectricCar(string a,string b,int c,int d=70):Car(a,b,c),battery1(d){} void info(); private: Battery battery1; }; void ElectricCar::info() { cout << "maker:\t" << get_maker() << endl; cout << "model:\t" << get_model() << endl; cout << "year:\t" << get_year() << endl; cout << "odometers:\t" << get_odometers() << endl; cout << "capacity:\t" << battery1.get_capacity() << endl; } #endif //
cpp:
#include <iostream> #include "electricCar.hpp" int main() { using namespace std; // test class of Car Car oldcar("dazhong", "baoma", 4016); cout << "--------oldcar's info--------" << endl; oldcar.update_odometers(25000); oldcar.info(); cout << endl; // test class of ElectricCar ElectricCar newcar("lpl", "lol", 2016,40); newcar.update_odometers(2500); cout << "\n--------newcar's info--------\n"; newcar.info(); }

pets.hpp:
#ifndef PETS_H #define PETS_H #include<iostream> #include<string> using namespace std; class MachinePets { public: MachinePets(const string s):nickname(s){} string get_nickname()const { return nickname; } virtual string talk() { return "宠物叫声"; } private: string nickname; }; class PetCats :public MachinePets { public: PetCats(const string s1):MachinePets(s1){} string talk() { return "miao~wu"; } }; class PetDogs :public MachinePets { public: PetDogs(const string s2):MachinePets(s2){} string talk() { return "wang~wang"; } }; #endif //
cpp:
#include <iostream> #include "pets.hpp" void play(MachinePets* ptr) { std::cout << ptr->get_nickname() << " says " << ptr->talk() << std::endl; } int main() { PetCats cat("miku"); PetDogs dog("da huang"); play(&cat); play(&dog);
}
