1.多态的基本语法
1.静态多态:函数重载和运算符重载属于静态多态,复用函数名
2.动态多态:派生类和虚函数实现运行时多态
静态多态和动态动态的区别:
静态多态的函数地址早绑定 - 编译阶段确定函数地址
动态多态的函数地址晚绑定 - 运行阶段确定函数地址
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
//虚构函数
virtual void speak()
{
cout<<"Animal speak !!!"<<endl;
}
};
class Cat:public Animal
{
public:
//重写父类中函数,函数名称、返回值类型、参数列表全部一致
void speak()
{
cout<<"Cat speak !!!"<<endl;
}
};
class Dog:public Animal
{
public:
void speak()
{
cout<<"Dog speak !!!"<<endl;
}
};
//function
void doSpeak(Animal &animal)
{
animal.speak();
}
void fun1()
{
//固定输出父类中的函数
Cat cat;
doSpeak(cat);
cout<<"---------------"<<endl;
Dog dog;
doSpeak(dog);
}
void fun2()
{
//父类中speak() 为虚函数,实现动态多态,即根据所传入的对象类型选择对应的函数
//动态多态满足条件
//1.有继承关系
//2.子类重写父类的虚函数
Cat cat;
doSpeak(cat);
cout<<"---------------"<<endl;
Dog dog;
doSpeak(dog);
}
int main()
{
fun1();
//输出
//Animal speak !!!
// ---------------
// Animal speak !!!
fun2();
//输出
//Cat speak !!!
// ---------------
// Dog speak !!!
return 0;
}
2.多态中的虚函数指针
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
//虚构函数
void speak()
{
cout<<"Animal speak !!!"<<endl;
}
};
class Cat:public Animal
{
public:
//重写父类中函数,函数名称、返回值类型、参数列表全部一致
void speak()
{
cout<<"Cat speak !!!"<<endl;
}
};
void fun3()
{
cout<<"size of Animal a is "<<sizeof(Animal)<<endl;
cout<<"size of Cat a is "<<sizeof(Cat)<<endl;
}
int main()
{
fun3();
// virtual void speak()
//输出
//size of Animal a is 4
//size of Cat a is 4
// void speak()
//输出
//size of Animal a is 1
//size of Cat a is 1
//virtual void speak() 虚函数指针占四个字节
return 0;
}
3.多态实际应用案例
#include <iostream>
#include <string>
using namespace std;
class AbstractCalculator
{
public:
//虚构函数
virtual int getResult()
{
return 0;
}
int m_a;
int m_b;
};
class Addition:public AbstractCalculator
{
public:
//重写父类中函数,函数名称、返回值类型、参数列表全部一致
int getResult()
{
return m_a + m_b;
}
};
class Subtraction:public AbstractCalculator
{
public:
int getResult()
{
return m_a - m_b;
}
};
//function
int doCalculate(AbstractCalculator &calculator)
{
return calculator.getResult();
}
void fun()
{
Addition add;
add.m_a = 10;
add.m_b = 190;
cout<<"Addition result is "<<doCalculate(add)<<endl;
Subtraction subtract;
subtract.m_a = 10;
subtract.m_b = 190;
cout<<"Subtraction result is "<<doCalculate(subtract)<<endl;
}
int main()
{
fun();
return 0;
}