码小余学习C++第8天笔记
子曰:“温故而知新,可以为师矣。”
多态存在的意义:
函数都能通过同一个接口调用到适合各自对象的实现方法。
多态包括:
- 编译时多态:函数重载就是一个例子。静态多态是编译器在编译期间完成的,编译器会根据实参类型来选择调用合适的函数,如果有合适的函数可以调用就调,没有的话就会发出警告或者报错
int Add(int left, int right)
{
return left + right;
}
double Add(double left, int right)
{
return left + right;
}
int main()
{
Add(10, 20); //调用的是两个int类型的那个方法
Add(10.0,20); //调用的是1个int类型、1个double类型的那个方法
return 0;
}
- 运行时多态:它是在程序运行时根据基类的引用(指针)指向的对象来确定自己具体该调用哪一个类的虚函数。
抽象类
#include <iostream>
using namespace std;
class TakeBus {
public:
void TakeBusToSubway() {
cout << "go to Subway--->please take bus of 318" << endl;
}
void TakeBusToStrtion() {
cout << "go to Station--->please Take Bus of 306 or 915" << endl;
}
};
//定义抽象类
class Bus {
public:
virtual void TakeBusToSomewhere(TakeBus& tb) = 0; //纯 虚 函 数
};
//抽象类必须被继承,并且实现抽象类
class Subway :public Bus {
virtual void TakeBusToSomewhere(TakeBus& tb) {
tb.TakeBusToSubway();
}
};
class Station :public Bus {
virtual void TakeBusToSomewhere(TakeBus& tb) {
tb.TakeBusToStrtion();
}
};
int main() {
TakeBus tb;
Bus* b = NULL;
for (int i = 1; i <= 10;i++) {
if ((rand() % i) & 1)
b = new Subway;
else
b = new Station;
}
b->TakeBusToSomewhere(tb);
delete b;
return 0;
}
分别使用对象、指针、引用来调用方法,我们发现他们输出的结果都一样。
#include <iostream>
using namespace std;
class Base {
public:
virtual void Funtest1(int i) {
cout << "Base::Funtest1()" << endl;
}
void Funtest2(int i) { //这个函数没有写virtual
cout << "Base::Funtest2()" << endl;
}
};
class Drived :public Base {
virtual void Funtest1(int i) {
cout << "Drived:Fubtest1()" << endl;
}
virtual void Funtest2(int i) {
cout << "Drived::Fubtest2()" << endl;
}
};
void TestVirtual(Base& b) {
b.Funtest1(1);
b.Funtest2(2);
}
int main() {
cout<< "----------使用对象来调用方法----------" << endl;
Base b;
Drived d;
TestVirtual(b); //输出:Base::Funtest1() Base::Funtest2()
TestVirtual(d); //输出:Drived:Fubtest1() Base::Funtest2()
/*
说明了(运行时多态的条件):
- 基类中必须包含虚函数,并且派生类中移动要对基类中的函数进行重写
- 通过基类对象的指针或者引用调用虚函数
*/
cout << "----------使用指针来调用方法----------" << endl;
Base x;
Drived y;
Base* px = &x;
Drived* py = &y;
TestVirtual(*px);
TestVirtual(*py);
cout << "----------使用引用来调用方法----------" << endl;
Base& rx = x;
Drived& ry = y;
TestVirtual(rx);
TestVirtual(ry);
return 0;
}
/*
注意:只能通过指针或引用实现多态,而不可以使用对象
*/
好好看我的代码中的注释