任務二:
1、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()
執行結果:
任務三:
car.hpp:
#include#includebattery.hpp:using
namespace
std;
class
car;
void
info()
void update_odometers(int
t)
};
#include#includeelectriccar.hpp:using
namespace
std;
class
battery
;
string get_capacity();
};
#include#includetask3.cpp:#include
"battery.hpp
"#include
"car.hpp
"using
namespace
std;
class electriccar:public
car;
void
info()
};
#include #include執行結果:"electriccar.hpp
"int
main()
任務四:
pets.hpp:
#include#includetask4.cpp:using
namespace
std;
class
machinepets
;
virtual
string talk();
string get_nickname();
};class petcats:public
machinepets
;
string talk();
};class petdogs:public
machinepets
;
string talk();
};
#include #include執行結果:"pets.hpp
"void play(machinepets *ptr)
intmain()
總結:任務二:
同名覆蓋原則:派生類與基類中有相同成員時,通過派生類物件使用的是派生類的同名成員;
二元作用域分辨符:類名稱::成員名,可以精確指定某個成員;
型別相容原則:在需要基類物件的任何地方都可以使用公有派生類的物件來替代:
(1)派生類物件可以隱含轉化為基類物件,b1=d1;
(2)派生類的物件可以初始化基類的引用,b &rb=d1;
(3)派生類的指標可以隱含轉化為基類的指標,pb1=&d1;
對於某個基類的多次引用,我們更推薦用virtual定義,這樣可以讓每個派生類對於同一函式擁有不同空間,更便於管理,避免基類中的某些函式在引用過程中不會產生歧義報錯
任務三是很普通的類的定義,主要加強了對繼承的應用
任務四就是對任務二的理解,virtual使得兩個派生類都能夠返回自己定義函式值
實驗四 繼承
簡單說明 基於虛基類的一些特性進行的驗證性實驗,理解並掌握虛基類的使用特點與注意事項。源 如下 關於虛基類已修改 include include definitation of graph class graph definition of rectangle,derived from graph ...
實驗四 繼承
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...