标签:cpp err none pre model class str 继承 mod
#ifndef BATTERY_H #define BATTERY_H class Battery { public: Battery(int battery = 70); int getbatterysize(); private: int batterysize; }; #endif
#include <iostream> using namespace std; #include "battery.h" Battery::Battery(int battery) : batterysize(battery) { } int Battery::getbatterysize(){ return batterysize; }
#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
#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; }
#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
#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; }
int &operator[](int a);
int &ArrayInt::operator[](int a) { return p[a]; }
总结
1 遇到了很多问题,比如继承时重复声明已经存在的私有成员
2 []的重载发现只能使用成员函数,不能使用友元函数。
标签:cpp err none pre model class str 继承 mod
原文地址:https://www.cnblogs.com/cwj0505/p/10890599.html