实验四

Battery.hpp

#ifndef BATTERY_HPP
#define BATTERY_HPP
#include<iostream>

class Battery{
    public:
        Battery(int a);
        int get_capacity(){return capacity;};
    private:
        int capacity;
};

Battery::Battery(int a=70):capacity(a){
};


#endif
View Code

Car.hpp

#ifndef CAR_HPP
#define CAR_HPP
#include<iostream>
using namespace std;

class Car{
    public:
        Car(string a,string b,int c);
        void info();
        void update_odometers(int newodometers);
    private:
        string maker;
        string model;
        int year;
        int odometers;
};

Car::Car(string a,string b,int c):maker(a),model(b),year(c),odometers(0){
};

void Car::info(){
    cout<<"制造商:    "<<maker<<endl;
    cout<<"型号:      "<<model<<endl;
    cout<<"生产年份:  "<<year<<endl;
    cout<<"行车旅程数:"<<odometers<<endl;
}

void Car::update_odometers(int newodometers){
    if(newodometers<odometers) cout<<"警告,数值不合法"<<endl;
    else odometers=newodometers;
}


#endif
View Code

ElectricCar.hpp

#ifndef ELECTRICCAR_HPP
#define ELECTRICCAR_HPP
#include"Battery.hpp"
#include"Car.hpp"
#include<iostream>
using namespace std;

class ElectricCar:public Car{
    public:
        ElectricCar(string a,string b,int c,int d=70);
        void info();
    private:
        Battery battery;
};

ElectricCar::ElectricCar(string a,string b,int c,int d):Car(a,b,c),battery(d){
};

void ElectricCar::info(){
    Car::info();
    cout<<"电池电量:"<<battery.get_capacity()<<"kwh"<<endl;
}

#endif
View Code

task3.cpp

#include <iostream>
#include "ElectricCar.hpp"

int main()
{
    using namespace std;

    // test class of Car
    Car oldcar("Audi", "a6", 2018);
    cout << "--------oldcar's info--------" << endl;
    oldcar.update_odometers(20000);
    oldcar.info();

    cout << endl;

    // test class of ElectricCar
    ElectricCar newcar("Tesla", "model sdd", 2017);
    newcar.update_odometers(3000);
    cout << "\n--------newcar's info--------\n";
    newcar.info();
}
View Code

 

 

 

pets.hpp

#ifndef PET_HPP
#define PET_HPP
#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 "gugugu~";};
    private:
        string nickname;
};

class PetCats:public MachinePets{
    public:
        PetCats(const string s):MachinePets(s){};
        string talk(){return "miaowu~";};
};

class PetDogs:public MachinePets{
    public:
        PetDogs(const string s):MachinePets(s){};
        string talk(){return "wangwang~";};
};

#endif
View Code

task4.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);
}
View Code

 

posted @ 2021-11-28 19:37  不愿再有早八  阅读(18)  评论(3编辑  收藏  举报