首页 > 其他 > 详细

实验四

时间:2019-05-22 01:15:30      阅读:122      评论:0      收藏:0      [点我收藏+]
battery.h:
#ifndef BATTERY_H
#define BATTERY_H

class Battery
{
    
    public: 
        friend class ElectricCar;
        Battery (string a1="70km/h")
        {
            a=a1;
        }
        Battery(Battery &p);
    private:
        string a;
};

 #endif


car.h:

 

#ifndef CAR_H

#define CAR_H

#include <string>

#include <iostream>

using namespace std;

class Car{
    public:
        Car (string maker1,string model1,int year1){
            maker=maker1;
            model=model1;
            year=year1;
            odometer=0;
        };
        friend ostream &operator <<(ostream &out, Car &c);
        void updateOdometer(int odometer1){
            if(odometer>odometer1)
            {
                cout<<"输入错误\n"; 
            }
            else
            {
            odometer=odometer1;
            }
        }; 
        friend class ElectricCar;
        
    protected:
        string maker;
        string model;
        int year;
        int odometer;
};

 

#endif


electricCar.h:

#ifndef  ELECTRICCAR_H

#define ELECTRICCAR_H

#include "car.h"

#include "battery.h"

class ElectricCar : public Car{
    private:
        Battery battery;
    public:
        ElectricCar(string maker2,string model2,int year2):Car(maker2,model2,year2)
        {};
        friend ostream &operator <<(ostream &out, ElectricCar &d);
        string gatbattery(){
            return battery.a;
        }

};

#endif


car.cpp:

#include "car.h"

ostream& operator<<(ostream &out, Car &c){
    out<<"maker:"<<c.maker<<"\n"<<"model:"<<c.model<<"\n"<<"year:"<<c.year<<"\n"<<"odometer:"<<c.odometer;
    return out;
};


electricCar.h:

#include "electricCar.h"

ostream& operator<<(ostream& out, const ElectricCar& ec) {

    Car tmp = ec;

    out << tmp << endl;

    out << "batterySize: " << (ec.battery).getSize()<<"-kWh";

    return out;

}


main.cpp:

#include <iostream>

using namespace std;

 

#include "car.h"

#include "electricCar.h"

 

int main() {
    // 测试Car类 
    Car oldcar("Audi","a4",2016);
    cout << "--------oldcar‘s info--------" << endl;
    oldcar.updateOdometer(25000);
    cout << oldcar << endl;

    // 测试ElectricCar类 
    ElectricCar newcar("Tesla","model s",2016);
    newcar.updateOdometer(2500);
    cout << "\n--------newcar‘s info--------\n"; 
    cout << newcar << endl;

    system("pause");
    
    return 0;
}

  

实验四

原文:https://www.cnblogs.com/hi-ypy/p/10903304.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!