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;
}