实验4 继承
battery.hpp:
#ifndef BATTRY_HPP
#define BATTRY_HPP
#include<iostream>
using namespace std;
class Battery{
private:
int capacity = 70;
public:
Battery(int x) : capacity(x) {}
int get_capacity(){
return capacity;
}
};
#endif
car.hpp:
#ifndef CAR_HPP
#define CAR_HPP
#include<iostream>
#include<string>
using namespace std;
class Car{
private:
string maker;
string model;
int year;
int odometers;
public:
Car(string a,string b,int c):maker(a),model(b),year(c),odometers(0){}
void info();
void update_odometers(int x);
};
void Car::info(){
cout << "maker: " << maker << endl;
cout << "model: " << model << endl;
cout << "year: " << year << endl;
if(odometers != 0)
cout << "odometers:" << odometers << endl;
}
void Car::update_odometers(int x){
if(x < odometers){
cout << "输入里程数数值有误!" << endl;
}
else
odometers = x;
}
#endif
electricCar.hpp:
#ifndef ELECTRIC_CAR_HPP
#define ELECTRIC_CAR_HPP
#include"car.hpp"
#include"battry.hpp"
#include<iostream>
#include<string>
using namespace std;
class ElectricCar : public Car{
private:
Battery battery = 70;
public:
ElectricCar(string a,string b,int c,int d):Car(a,b,c),battery(d){}
void info();
};
void ElectricCar::info(){
Car::info();
cout << "capacity: " << battery.get_capacity() << "-kwh" << endl;
}
#endif
task3.cpp:
#include <iostream>
#include "electricCar.hpp"
int main()
{
using namespace std;
// test class of Car
Car oldcar("Audi", "a4", 2016);
cout << "--------oldcar's info--------" << endl;
oldcar.update_odometers(25000);
oldcar.info();
cout << endl;
// test class of ElectricCar
ElectricCar newcar("Tesla", "model s", 2016);
newcar.update_odometers(2500);
cout << "\n--------newcar's info--------\n";
newcar.info();
}
运行结果:

pets.hpp:
#ifndef PETS_HPP
#define PETS_HPP
#include<iostream>
#include<string>
using namespace std;
class MachinePets{
private:
string nickname;
public:
MachinePets(const string s):nickname(s){}
const string get_nickname(){
return nickname;
}
virtual string talk(){
return "叫声";
}
};
class PetCats : public MachinePets{
public:
PetCats(const string s):MachinePets(s){}
string talk(){
return "miao wu~";
}
};
class PetDogs : public MachinePets{
public:
PetDogs(const string s):MachinePets(s){}
string talk(){
return "wang wang~";
}
};
#endif
task4.cpp:
#include <iostream>
#include "pets.hpp"
void play(MachinePets *ptr)
{
std::cout << ptr->get_nickname() << " says " << ptr->talk() << std::endl;
}
int main()
{
PetCats cat("miku");
PetDogs dog("da huang");
play(&cat);
play(&dog);
}
运行结果:


浙公网安备 33010602011771号