实验4 继承
task3源代码
battery.hpp
#include<iostream> using namespace std; class Battery { public: Battery(int a=70):capcity(a){} void get_capcity() { cout << capcity << endl; } private: int capcity; };
car.hpp
#pragma once #include<iostream> #include<string> #include<iomanip> using namespace std; class Car { public: Car(string a,string b,int y):year(y),maker(a),model(b), odometers(0){} Car(){} void update_odometers(int a) { if (odometers < a) odometers = a; else cout << "input error" << endl; } void info() { cout << "maker:"<<setw(10) << maker << endl; cout << "model:" << setw(10) << model << endl; cout << "year:" << setw(10) << year << endl; cout << "odometers:" << setw(10) << odometers << endl; } private: int year; int odometers; string maker; string model; };
electricCar.h
#pragma once #include<iostream> #include"car.h" #include"battery.h" #include<string> class ElectricCar:public Car { public: ElectricCar(string a,string b,int y):Car(a,b,y) {} private: Battery battery; };
task4源代码
pets.hpp
#pragma once #include<iostream> #include<string> using namespace std; class MachinePets { public: MachinePets(const string s):nickname(s){} virtual string talk() { return word; } string get_nickname() { return nickname; } private: string nickname; string word=" "; }; class PetCats : public MachinePets { public: PetCats(const string s):MachinePets(s){} string talk(){ return word; } private: string word = "miao wu~"; }; class PetDogs : public MachinePets { public: PetDogs(const string s) :MachinePets(s) {} string talk() { return word; } private: string word = "wang wang~"; };
main.cpp
#include <iostream> #include "pets.h" 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号