如何实现运行时刻的多态?(c++)
生活随笔
收集整理的這篇文章主要介紹了
如何实现运行时刻的多态?(c++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先,要明確運行時刻的多態(tài)依賴于類的繼承與虛函數。
(可以去看我之前寫的文章)
基本做法是:在基類與派生類中定義函數原型相同的兩個虛函數,然后定義基類的指針,用積累的指針指向不同的派生類對象,通過虛函數即可實現運行時多態(tài)。
代碼例子:
#include <iostream> using namespace std;class vehicle {public:vehicle(int n = 0, int m = 0) { //初始基類的構造函數axspeed = n;//對數據成員進行賦值Weigh = m;}virtual void run() { //初始基類的兩個成員函數cout << "vehicle run!" << endl;}void stop() {cout << "vehicle stop!" << endl;}private:int axspeed;int Weigh; };class bicycle : virtual public vehicle {public:bicycle(int x = 0, int y = 0, int z = 0) : vehicle(x, y) //中間派生類的構造函數,//需要為初始基類提供形參{Height = z;}void run() {cout << "bicycle run!" << endl;}void stop() {}private:int Height; };class motorcar : virtual public vehicle {public:motorcar(int x = 0, int y = 0, int z = 0) : vehicle(x, y) //中間派生類的構造函數,//需要為初始基類提供形參{SeatNun = z;}void run() {cout << "motorcar run!" << endl;}void stop() {}private:int SeatNun; };class motorbicycle : public bicycle, public motorcar {public:void run() {cout << "motorbicycle run!" << endl;}void stop() {} };int main() {vehicle v;bicycle b;motorcar mot;motorbicycle mo;v.run();b.run();mot.run();mo.run();vehicle *ve = new vehicle;ve = &v;ve->run();ve = &b;ve->run();ve = &mot;ve->run();ve = &mo;ve->run();return 0; }希望對大家有幫助!!!
總結
以上是生活随笔為你收集整理的如何实现运行时刻的多态?(c++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求n个数的最大公因数和最小公倍数(c)
- 下一篇: c++重载自增与自减运算符(前置与后置)