實驗四 繼承

2022-09-10 08:09:09 字數 2525 閱讀 3596

task2.cpp

#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

intmain()

改動前的結果:

改動後的結果:

同名覆蓋原則:派生類與基類中有相同成員時,若未強行指明,則通過派生類物件使用的是派生類的同名成員;如果要通過派生類的物件訪問基類被覆蓋的同名成員,則需要加物件名.基類名::同名成員來限定;

二元作用域分辨符:在多重繼承的情況下,如果兩個基類中存在相同的變數名,可以使用作用域運算子來進行區分;

型別相容原則:指在需要基類物件的任何地方,都可以使用公有派生類的物件來替代。通過公有繼承,派生類得到了基類中除建構函式、析構函式之外的所有成員。

battery.hpp

#include using

namespace

std;

class

battery

;

intget_capacity()

private

:

intcapacity;

};

car.hpp

#include #include 

#include

using

namespace

std;

class

car;

void

info()

void update_odometers(int

n)

private

:

string

maker;

string

model;

intyear;

intodometers;

};

electriccar.hpp

#include #include 

"car.hpp

"#include

"battery.hpp

"using

namespace

std;

class electriccar : public

car;

void

info()

private

: battery battery;

};

task3.cpp

#include #include 

"electriccar.hpp

"int

main()

執行結果:

執行結果:

實驗四 繼承

簡單說明 基於虛基類的一些特性進行的驗證性實驗,理解並掌握虛基類的使用特點與注意事項。源 如下 關於虛基類已修改 include include definitation of graph class graph definition of rectangle,derived from graph ...

實驗四 繼承

任務二 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...