實驗四 繼承

2022-09-10 07:54:12 字數 3122 閱讀 3653

簡單說明:基於虛基類的一些特性進行的驗證性實驗,理解並掌握虛基類的使用特點與注意事項。

源**如下(關於虛基類已修改):

#include #include // definitation of graph

class graph

};// definition of rectangle, derived from graph

class rectangle : public graph

};// definition of circle, derived from graph

class circle : public graph

};// definitaion of fun(): as a call inte***ce

void fun(graph *ptr)

// test

int main()

測試結果(未修改前):

測試結果(修改後):

歸納與總結:

​ 如果乙個類有直接或間接的虛基類,則先執行虛基類的建構函式。

​ 如果該類有其他基類,則按照它們在繼承宣告列表中的出現的次序,分別執行它們的建構函式,但構造過程中,不再執行它們的虛基類的建構函式。

簡單說明:使用類的組合和繼承模擬簡單的車輛資訊管理。

​ 為了對車量基本資訊進行管理,對現實世界車量基本資訊抽象後,抽象出car類、electriccar類、battery類,它們之間的關係描述如下:

​ electriccar類公有繼承自car類,electriccar中新增資料成員為battery類物件。

類定義與實現battery.hpp**如下:

#ifndef battery_cpp

#define battery_cpp

#include using namespace std;

class battery ;

battery::battery(int c) : capacity(c) {}

void battery::get_capacity()

#endif

類定義與實現car.hpp**如下:

#ifndef car_hpp

#define car_hpp

#include #include using namespace std;

class car ;

car::car(string ma, string mo, int ye, int od = 0): maker(ma), model(mo), year(ye), odometers(od)

void car::info()

void car::update_odometers(int newo)

#endif // !car_hpp

類定義與實現electriccar.hpp**如下:

#ifndef electriccar_hpp

#define electriccar_hpp

#include #include #include "car.hpp"

#include "battery.hpp"

using namespace std;

class electriccar : public car ;

electriccar::electriccar(string ma, string mo, int year, int od = 0, int ba = 70): car(ma, mo, year, od), battery(ba)

void electriccar::info()

#endif // !electriccar_hpp

主程式task3.cpp**如下:

#include #include "electriccar.hpp"

int main()

使用更改的資料的測試結果:

簡單說明:使用類的繼承,模擬簡單的機器寵物。

​ 對機器寵物進行抽象後,抽象出三個簡單的類:

​ 機器寵物類machinepets、寵物貓類petcats、寵物狗類petdogs。

類定義與實現pets.hpp**如下:

#ifndef pets_hpp

#define pets_hpp

#include #include using namespace std;

class machinepets

virtual string talk();

};machinepets::machinepets(const string s): nickname(s)

string machinepets::talk()

class petcats : public machinepets ;

petcats::petcats(const string s) : machinepets(s)

string petcats::talk()

class petdogs : public machinepets ;

petdogs::petdogs(const string s) : machinepets(s)

string petdogs::talk()

#endif // !pets_hpp

主程式task3.cpp**如下:

#include #include "pets.hpp"

void play(machinepets* ptr)

int main()

測試結果如下:

實驗四 繼承

任務二 1 cpp include include definitation of graph class graph definition of rectangle,derived from graph class rectangle public graph definition of circ...

實驗四 繼承

task2.cpp include include definitation of graph class graph definition of rectangle,derived from graph class rectangle public graph definition of circ...

實驗四 繼承

task2.cpp include include definitation of graph class graph definition of rectangle,derived from graph class rectangle public graph definition of circ...