实验4 继承
electricCar.hpp
#include<string> using namespace std; class Battery{ public: Battery(int cap=70); ~Battery(); int get_capacity(); private: int capacity; }; class Car{ public: Car(string maker,string model,int year); ~Car(); void info(); int update_odometers(int odo); string maker; string model; int year; int odometers; }; class ElectricCar : public Car{ public: ElectricCar(string maker,string model,int year); ~ElectricCar(); void info(); private: Battery battery; };
electricCar.cpp
#include"electricCar.hpp" #include<iostream> using namespace std; Car::Car(string maker,string model,int year){ maker=maker;model=model;year=year;odometers=0; } Car::~Car(){ } int Car::update_odometers(int odo){ if(odo<odometers){ cout<<"参数错误"<<endl; return odometers; } odometers=odo; return odometers; } void Car::info(){ cout<<"制造商: "<<maker<<endl; cout<<"型号: "<<model<<endl; cout<<"生产年份:"<<year<<endl; cout<<"里程数: "<<odometers<<endl; } ElectricCar::ElectricCar(string maker,string model,int year):Car(maker,model,year){ } ElectricCar::~ElectricCar(){ } void ElectricCar::info(){ cout<<"制造商: "<<maker<<endl; cout<<"型号: "<<model<<endl; cout<<"生产年份:"<<year<<endl; cout<<"里程数: "<<odometers<<endl; cout<<"电量: "<<battery.get_capacity()<<endl; } Battery::Battery(int cap){ capacity=cap; } Battery::~Battery(){ } int Battery::get_capacity(){ return capacity; }
Pet.cpp
#pragma once #include<iostream> #include<string> using namespace std; class MachinePets{ public: MachinePets(const string s) :nickname(s) {} string get_nickname() const{ return nickname; } ~MachinePets() = default; virtual string talk() { return " "; } private: string nickname; }; class PetCats :public MachinePets{ public: PetCats(const string s) :MachinePets(s) { } string talk() { return "miao wu~"; } ~PetCats() = default; }; class PetDogs :public MachinePets { public: PetDogs(const string s) :MachinePets(s) { } string talk() { return "wang wang~"; } ~PetDogs() = default; };