您当前的位置: 首页 > 

txwtech

暂无认证

  • 2浏览

    0关注

    813博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

cc26a_demo-CppPrimer_动态绑定_多态-代码示范

txwtech 发布时间:2020-01-14 15:46:47 ,浏览量:2

//多态性     //从派生类到基类的转换     //引用或者指针既可以指向基类对象,也可以指向派生类对象     //只有通过引用或者指针调用虚函数才会发生动态绑定。     //为什么定义虚的函数?可以重新定义。只有虚函数才可以重写,(基类或者派生类里面)

动态绑定的方法,执行出来的效果,就是多态

 

#include //txwtech-202001
#include //多态,动态绑定

using namespace std;//导入名称空间

class Animal
{
	//成员略
};

class Dog :public Animal
{
	//成员略
};
class Cat :public Animal
{

};
class Item_base
{
public:
	//int x;
	Item_base(const std::string &book = "",
		double sales_price = 0.0) :isbn(book), price(sales_price) {}//构造函数
	std::string book() const
	{
		return isbn;
	}
	virtual double net_price(size_t n) const//为什么定义虚的函数?可以重新定义。只有虚函数才可以重写
	{
		return n * price;
	}

private://类的内部使用
	std::string isbn;
protected://专门用来做继承用的
	double price;

};
class Bulk_item :public Item_base
{
public:
	Bulk_item(const std::string &book = "", double sales_price = 0.0,
		size_t qty = 0, double disc_rate = 0.0) :
		Item_base(book, sales_price), min_qty(qty), discount(disc_rate) {}
	void test()
	{
		//cout             
关注
打赏
1665060526
查看更多评论
0.0394s