码迷,mamicode.com
首页 > 其他好文 > 详细

实验4

时间:2019-05-19 20:53:15      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:cpp   err   none   pre   model   class   str   继承   mod   

技术图片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 []的重载发现只能使用成员函数,不能使用友元函数。

 

实验4

标签:cpp   err   none   pre   model   class   str   继承   mod   

原文地址:https://www.cnblogs.com/cwj0505/p/10890599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!