首页 > 其他 > 详细

实验四

时间:2019-05-22 01:15:30      阅读:42      评论:0      收藏:0      [点我收藏+]

标签:prot   sin   错误   cout   .cpp   pro   输入   car   clu   

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;
}

  

实验四

标签:prot   sin   错误   cout   .cpp   pro   输入   car   clu   

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

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号