4.7.2多态案例计算器类
#include <iostream>
using namespace std;
#include <string>
class Calculator
{
public:
int getresult(string oper)
{
if (oper == "+")
{
return m_num1 + m_num2;
}
else if (oper == "-")
{
return m_num1 - m_num2;
}
else if (oper == "*")
{
return m_num1 * m_num2;
}
}
int m_num1;
int m_num2;
};
void test01()
{
Calculator c;
c.m_num1 = 10;
c.m_num2 = 10;
cout << c.m_num1 << "+"
<< c.m_num2 << "="
<< c.getresult("-") << endl;
}
class Abstractcal
{
public:
virtual int getresult()
{
return 0;
}
int m_num1;
int m_num2;
};
class addcal :public Abstractcal
{
public:
virtual int getresult()
{
return m_num1 + m_num2;
}
};
class subcal :public Abstractcal
{
public:
virtual int getresult()
{
return m_num1 - m_num2;
}
};
class chengcal :public Abstractcal
{
public:
virtual int getresult()
{
return m_num1 * m_num2;
}
};
void test02()
{
Abstractcal *abc = new addcal;
abc->m_num1 = 10;
abc->m_num2 = 10;
cout << abc->getresult() << endl;
delete abc;
abc = new subcal;
abc->m_num1 = 50;
abc->m_num2 = 10;
cout << abc->getresult() << endl;
delete abc;
}
int main4_7_2()
{
test02();
system("pause");
return 0;
}
4.7.1多态的概念
#include <iostream>
using namespace std;
class animal
{
public:
virtual void speak()
{
cout << "动物说话" << endl;
}
};
class cat :public animal
{
public:
void speak()
{
cout << "小猫说话" << endl;
}
};
class dog :public animal
{
public:
void speak()
{
cout << "狗说话" << endl;
}
};
void dospeak(animal &animal)
{
animal.speak();
}
void test01()
{
cat cat;
dospeak(cat);
dog dog;
dospeak(dog);
}
void test02()
{
cout << sizeof(animal) << endl;
}
int main4_7_1()
{
test02();
system("pause");
return 0;
}