多态
多态分为两种:
- 静态多态:函数重载 和 运算符重载 属于静态多态,复用函数名
- 动态多态:派生类 和 虚函数 实现运行时多态
- 静态多态函数地址早绑定--编译阶段确定函数地址
- 动态多态函数地址晚绑定--运行阶段确定函数地址
virtual //修饰虚函数,使之变为动态
多态特点
- 代码结构清晰
- 可读性强
- 利于前期和后期的扩展及维护
练习--计算器的封装、继承、多态
class Compute
{
public:
virtual int getResult()
{
return 0;
}
void assagin(int num1, int num2)
{
this->m_num1 = num1;
this->m_num2 = num2;
}
int m_num1;
int m_num2;
};
class AddCompute : public Compute
{
public :
int getResult()
{
return m_num1 + m_num2;
}
};
class SubCompute : public Compute
{
public:
int getResult()
{
return m_num1 - m_num2;
}
};
class MulCompute : public Compute
{
public:
int getResult()
{
return m_num1 * m_num2;
}
};
class DivCompute : public Compute
{
public:
int getResult()
{
return m_num1 / m_num2;
}
};
void test()
{
Compute *p1 = new AddCompute;
p1->assagin(20, 30);
cout << p1->m_num1 << " + " << p1->m_num2 << " = " << p1->getResult() << endl;
Compute *p2 = new SubCompute;
p2->assagin(20, 30);
cout << p2->m_num1 << " - " << p2->m_num2 << " = " << p2->getResult() << endl;
Compute *p3 = new MulCompute;
p3->assagin(20, 30);
cout << p3->m_num1 << " * " << p3->m_num2 << " = " << p3->getResult() << endl;
Compute *p4 = new DivCompute;
p4->assagin(100,10);
cout << p4->m_num1 << " / " << p4->m_num2 << " = " << p4->getResult() << endl;
delete p1; p1 = nullptr;
delete p2; p2 = nullptr;
delete p3; p3 = nullptr;
delete p4; p4 = nullptr;
}
int main()
{
test();
system("pause");
return 0;
}