实验
#ifndef BATTERY_H #define BATTERY_H class Battery{ public: Battery(int b=70); int bb(); private: int batterySize; }; #endif
#include "battery.h" #include <iostream> using namespace std; Battery::Battery(int b):batterySize(b){ } int Battery::bb(){ return batterySize; }
#ifndef CAR_H #define CAR_H #include <iostream> #include <string> using std::string; class Car{ public: Car(string ma,string mo,int ye,int od=0); friend std::ostream & operator << (std::ostream &out,Car &c); int updateOdometer(int a); string mak(); string mod(); int yea(); int odo(); private: string maker; string model; int year; int odometer; }; #endif
#include "car.h" #include <iostream> using namespace std; Car::Car(string ma,string mo,int ye,int od):maker(ma),model(mo),year(ye),odometer(od) { } string Car::mak(){ return maker; } string Car::mod(){ return model; } int Car::yea(){ return year; } int Car::odo(){ return odometer; } std::ostream & operator <<(std::ostream &out,Car &c){ out<<"maker: "<<c.maker<<endl <<"model: "<<c.model<<endl <<"year: "<<c.year<<endl <<"odometer: "<<c.odometer<<endl; return out; } int Car::updateOdometer(int a){ if(odometer<=a) cout<<"error!"<<endl; else{ odometer=a; cin>>odometer; } return odometer; }
#ifndef ELECTRICCAR_H #define ELECTRICCAR_H #include "car.h" #include "battery.h" #include <string> using std::string; class ElectricCar:public Car,public Battery{ public: ElectricCar(string ma,string mo,int ye,int od=0); friend std::ostream & operator <<(std::ostream &out,Car &c); }; #endif
#include "car.h" #include "battery.h" #include "electricCar.h" #include <iostream> using namespace std; ElectricCar::ElectricCar(string ma,string mo,int ye,int od):Car(ma,mo,ye,od){ } std::ostream & operator<<(std::ostream &out,ElectricCar &c){ out<<"maker: "<<c.mak()<<endl <<"model: "<<c.mod()<<endl <<"year: "<<c.yea()<<endl <<"odomter: "<<c.odo()<<endl <<"batterySize: "<<c.bb()<<"-KWh"<<endl; return out; }
#include "arrayInt.h" #include <iostream> #include <cstdlib> 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<size; i++) p[i] = value; } ArrayInt::~ArrayInt() { delete[] p; } void ArrayInt::print() { for(int i=0; i<size; i++) cout << p[i] << " "; cout << endl; } int &ArrayInt:: operator [](int v){ return p[v]; }
#ifndef ARRAY_INT_H #define ARRAY_INT_H class ArrayInt{ public: ArrayInt(int n, int value=0); ~ArrayInt(); int & operator [] (int a); void print(); private: int *p; int size; }; #endif
#include <iostream> using 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; }
实验总结:参照了之前做的实验和书本,能够更加熟练的运用构造函数,同时也复习了不太熟悉的友元和重载函数