4.7.2多态案例计算器类

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()
{
	//test01();
	test02();

	system("pause");
	return 0;
}

4.7.1多态的概念


#include <iostream>
using namespace std;
/*
动态多态满足条件
1,有继承关系
2.子类重写父类的虚函数

如何使用:
父类的指针或引用指向子类的对象
*/

class animal
{
public:
	virtual void speak()
	{
		cout << "动物说话" << endl;
	}
};
class cat :public animal
{
public:
	  void speak()
	{
		cout << "小猫说话" << endl;
	}
};
//地址早绑定

//如果想让猫说话,这个函数地址(animal &animal)就不能提前绑定
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()
{
	//test01();
	test02();


	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cdbycd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值