题一:
#ifndef BATTERY_H#define BATTERY_Hclass Battery {public: Battery(int x = 70); int getbattery()const;private: int batterySize; };#endif
#ifndef CAR_H#define CAR_H#include#include using namespace std;class Car{public: Car(string maker1,string model1,int year1,int odometer1=0) :maker(maker1), model(model1), year(year1), odometer(odometer1) {} friend ostream& operator<<(ostream &out,Car &c); void updateOdometer(int number); string maker; string model; int year; int odometer; };#endif
#ifndef ELECTRICCAR_H#define ELECTRICCAR_H#include"car.h"#include"battery.h"#include#include class ElectricCar:public Car,public Battery{public: ElectricCar(string maker2, string model2, int year2, int odometer2 = 0) :Car(maker2, model2, year2, odometer2) { } friend ostream& operator<<(ostream &outCar,ElectricCar &d); void updateOdometer(int number);private: Battery battery;};#endif
#include"Battery.h"Battery::Battery(int x){batterySize=x; }int Battery::getbattery()const {return batterySize;}
#include#include #include "Car.h"using namespace std;void Car:: updateOdometer(int number){ if(number
#include"electricCar.h"#includeusing namespace std;ostream& operator<<(ostream &out,ElectricCar &d){ out< < < < < < < <
#includeusing 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;}
运行截图
题目二:
#ifndef ARRAY_INT_H#define ARRAY_INT_Hclass ArrayInt{public:ArrayInt(int n, int value=0);~ArrayInt();int &operator[](int x); void print();private:int *p;int size;};#endif
#include "arrayInt.h"#include#include using std::cout;using std::endl;ArrayInt::ArrayInt(int n, int value): size(n) {p = new int[size];if (p == NULL) {cout << "fail to mallocate memory" << endl;exit(0);}for(int i=0; i
#includeusing namespace std;#include "arrayInt.h"int main() { // 定义动态整型数组对象a,包含2个元素,初始值为0 ArrayInt a(2); a.print(); // 定义动态整型数组对象b,包含3个元素,初始值为6 ArrayInt b(3, 6); b.print(); // 通过对象名和下标方式访问并修改对象元素 b[0] = 2; cout << b[0] << endl; b.print(); system("pause"); return 0;}
实验总结:
1.在写第一道题时,起初在定义car类之前没有使用ifndef def语句,导致了Car类的重定义,应该是C++标准类中有Car类了,浪费了一些时间。
2.之前没有明白运算符重载是怎么实现参数传递的,后来想明白了,就和函数一样。
3.第一道题中分别需要Car类带默认形参值的构造函数和ElectricCar类带默认形参值的构造函数,一开始没考虑太多,直接写了两个构造函数,编译时出错了,因为ElectricCar继承了Car类,有两个构造函数,计算机不知道选哪个,后来作了一些改动。当然不止一种解决办法,虚基类应该也可以解决。