小白成长之路(7)--C++多层派生类继承实例(期中考试)

来源:互联网 发布:有哪些视频剪辑软件 编辑:程序博客网 时间:2024/06/06 03:59

没有一点点防备,专业老师来了一次突击期中考试,题目倒是不难,可做的时候总是有点紧张,以至于刚写完红线不少,不过还好,完美通关,特在此贴上代码,请各位大神帮助指出不足之处,给小白指点指点,再次感谢(小白代码,可笑之处轻喷)。

题目:
定义一个父类Vehicle,包含一个私有变量name,一个函数run();
定义两个子类Car,Plane,各包含一个私有变量move(运行方式);
输出结果:Car is running through the wheel.
Plane is running through the wings.

(1).首先定义类文件和头文件

这里写图片描述

(2).Vehicle头文件代码

#pragma once#include <iostream>#include <string>using namespace std;class Vehicle {private:    string name;public:    Vehicle(string name);//含参数构造函数    ~Vehicle();public:    void set_name(string name);    string get_name();public:    virtual void run();};

(3).Vehicle类文件代码

#pragma once#include "Vehicle.h"Vehicle::Vehicle(string name) {//含参数构造函数    this->name = name;}Vehicle::~Vehicle() {}void Vehicle::set_name(string name) {    this->name = name;}string Vehicle::get_name() {    return name;}void Vehicle::run() {    cout << name << " " << "is running" << " " ;}

(4).Car头文件代码

#pragma once#include "Vehicle.h"class Car : public Vehicle {private:    string move;public:    Car(string name, string move);    ~Car();public:    void set_move(string move);    string get_move();public:    void run();};

(5).Car类文件代码

#include "Car.h"Car::Car(string name, string move) :Vehicle(name) {    this->move = move;}Car::~Car() {//析构函数}void Car::set_move(string move) {    this->move = move;}string Car::get_move() {    return move;}void Car::run() {    Vehicle::run();    cout << " " << "through" << " " << move << endl;}

(6).Plane头文件代码

#pragma once#include "Vehicle.h"class Plane : public Vehicle {private:    string move;public:    Plane(string name, string move);    ~Plane();public:    void set_move(string move);    string get_move();public:    void run();};

(7).Plane类文件代码

#include "Plane.h"Plane::Plane(string name, string move) :Vehicle(name) {    this->move = move;}Plane::~Plane() {//析构函数}void Plane::set_move(string move) {    this->move = move;}string Plane::get_move() {    return move;}void Plane::run() {    Vehicle::run();    cout << " " << "through" << " " << move << endl;}

(8).main文件代码

#pragma once#include "Vehicle.h"#include "Car.h"#include "Plane.h"#include <iostream>using namespace std;void show_vechiel(Vehicle* v) {     v->run();}int main() {    Vehicle* d = new Car("Car","the wheel.");    show_vechiel(d);    delete d;    Vehicle* p = new Plane("Plane", "the wings.");    show_vechiel(p);    delete p;    cin.get();}

运行结果:
这里写图片描述

如有不足之处请各位大神不吝赐教,谢谢!

原创粉丝点击