标签:string Car hpp 实验 MachinePets include public
任务三
Battery.hpp
#pragma once #include<iostream> using namespace std; class Battery { public: Battery(float n=70) :capacity{ n } {} float get_capacity() { return capacity; } ~Battery() = default; private: float capacity; };
Car.hpp
#pragma once #include<iostream> using namespace std; class Car { public: Car(string m="???", string mo="???", int y=0 ) { maker = m; model = mo; year = y; odometers = 0; } void info() { cout << "maker:\t\t" << maker << endl; cout << "model:\t\t" << model << endl; cout << "year:\t\t" << year << endl; cout << "odometers:\t" << odometers << endl; } void update_odometers(float o) { if (o <= odometers) { cout << "更新信息有误。" << endl; } else odometers = o; } ~Car() = default; private: string maker, model; int year; float odometers; };
ElectricCar.hpp
#pragma once
#include<iostream>
#include"Car.hpp"
#include"Battery.hpp"
using namespace std;
class ElectricCar :public Battery, public Car
{
public:
ElectricCar(string m = "???", string mo = "???", int y = 0, float od = 70): Car(m, mo, y), Battery(od){
}
void info() {
Car::info();
cout << "capacity:\t" << get_capacity() << "-KWh" << endl;
}
~ElectricCar() = default;
};
main.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
#pragma once #include<iostream> #include<string> using namespace std; class MachinePets { public: MachinePets(const string s) { nickname = s; } const string get_nickname() { return nickname; } virtual string talk() { return "a"; }
~MachinePets()=default; private: string nickname; }; class PetCats:public MachinePets { public: PetCats(const string c) :MachinePets(c){ } string talk() { return "miao wu~"; }
~PetCats()=default; }; class PetDogs:public MachinePets { public: PetDogs(const string s):MachinePets(s){} string talk() { return "wang wang~"; }
~PetDogs()=default; };
main.cpp
#pragma once #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); }
运行图:
总结:
同名覆盖原则:通过成员调用时,默认调用派生类的成员。若通过指针调用,则调用基类的。
标签:string,Car,hpp,实验,MachinePets,include,public 来源: https://www.cnblogs.com/jlyyyhwlgsk/p/15612881.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。