1、重載和多態的關係:
多態分爲靜態多態和動態多態:
靜態多態 包含 重載和泛型編程
動態多態 ---》虛函數
2、重載案例:
//
// Created by luzhongshan on 10/18/19.
//
#include "stdlib.h"
#include "iostream"
using namespace std;
int Add(int left, int right)
{
return left + right;
}
double Add(double left, int right)
{
cout<<"sizeof a: "<< sizeof(left)<<"sizeof b:"<< sizeof(right)<<endl;
return left + right;
}
int main()
{
int a=Add(10, 20);
cout<<"a "<<a<<endl;
//Add(10.0, 20.0); //這是一個問題代碼
double b =Add(10.0,20); //正常代碼
cout<<"sizeof b"<< sizeof(b)<<"b "<<b<<endl;
return 0;
}
3、虛函數案例:
//
// Created by luzhongshan on 10/18/19.
//
#include "iostream"
using namespace std;
class TakeBus
{
public:
void TakeBusToSubway()
{
cout << "go to Subway--->please take bus of 318" << endl;
}
void TakeBusToStation()
{
cout << "go to Station--->pelase Take Bus of 306 or 915" << endl;
}
};
//知道了去哪要做什麼車可不行,我們還得知道有沒有這個車
class Bus
{
public:
virtual void TakeBusToSomewhere(TakeBus& tb) = 0; //???爲什麼要等於0
};
class Subway:public Bus
{
public:
virtual void TakeBusToSomewhere(TakeBus& tb)
{
tb.TakeBusToSubway();
}
};
class Station :public Bus
{
public:
virtual void TakeBusToSomewhere(TakeBus& tb)
{
tb.TakeBusToStation();
}
};
int main()
{
TakeBus tb;
Bus* b = NULL;
Bus* a = NULL;
//假設有十輛公交車,如果是奇數就是去地鐵口的,反之就是去火車站的
b = new Subway;
a = new Station;
b->TakeBusToSomewhere(tb);
a->TakeBusToSomewhere(tb);
delete b;
return 0;
}