实验4

main.cpp
#ifndef BATTERY_H
#define BATTERY_H

class Battery {
public:
    Battery(int battery = 70);
    int getbatterysize();
private:
    int batterysize;
};

#endif
battery.h
#include <iostream>
using namespace std;
#include "battery.h"

Battery::Battery(int battery) : batterysize(battery) {
}

int Battery::getbatterysize(){
    return batterysize;
}
battery.cpp
#ifndef CAR_H
#define CAR_H
#include <string>
#include <iostream>
using namespace std;
class Car {
public:
    Car(string ma, string mo, int y, int od = 0);
    friend ostream &operator<<(ostream &out, Car &c);
    void updateOdometer(int up);
    string getmaker();
    string getmodel();
    int getyear();
    int getodometer();

private:
    string maker;
    string model;
    int year;
    int odometer;
};

#endif
car.h
#include <iostream>
#include "car.h"
#include <string>
using namespace std;

Car::Car(string ma, string mo, int y, int od) :maker(ma), model(mo), year(y), odometer(od) {
}
ostream &operator<<(ostream &out, Car &c) {
    out << "maker: " << c.maker << endl
        << "model: " << c.model << endl
        << "year: " << c.year << endl
        << "odometer: " << c.odometer;
    return out;
}
void Car::updateOdometer(int up) {
    if (up < odometer)
        cout << "update value error." << endl;
    else
        odometer = up;
}

string Car::getmaker() {
    return maker;
}

string Car::getmodel() {
    return model;
}

int Car::getyear() {
    return year;
}

int Car::getodometer() {
    return odometer;
}
car.cpp
#ifndef ELECTRIC_CAR_H
#define ELECTRIC_CAR_H
#include "car.h"
#include "battery.h"
#include <string>
class ElectricCar : public Car, public Battery {
public:
    ElectricCar(string ma, string mo, int y, int od = 0, int ba = 70);
    friend ostream &operator<<(ostream &out, ElectricCar &e);

};

#endif
eletriccar.h
#include "car.h"
#include "battery.h"
#include "ElectricCar.h"
#include <string>
#include <iostream>
using namespace std;

ElectricCar::ElectricCar(string ma, string mo, int y, int od, int ba) :Car(ma, mo, y, od), Battery(ba) {
}

ostream &operator<<(ostream &out, ElectricCar &e)
{
    out << "maker:  " << e.getmaker() << endl
        << "model:  " << e.getmodel() << endl
        << "year:  " << e.getyear() << endl
        << "odometer:  " << e.getodometer() << endl
        << "batterySize:  " << e.getbatterysize() << "-kWh";
    return out;
}
eletriccar.cpp

int &operator[](int a);
int &ArrayInt::operator[](int a) {
    return p[a];
}

总结

1 遇到了很多问题,比如继承时重复声明已经存在的私有成员

2 []的重载发现只能使用成员函数,不能使用友元函数。

 

posted on 2019-05-19 20:20  褚先生  阅读(70)  评论(0)    收藏  举报

导航